Preselect <option> in <select> while using ng
I am using AngularJS and HTML. Is there a way to pre-select an option in an option tag if my options are being generated using an ng-repeat? See below code snippet for example:
HTML:
<select class="form-control" id="eventSelectMenu">
<option ng-repeat="option in allEventData">{{option.name}}</option>
</select>
I have tried solutions presented here and here, but none have been successful.
Thank you for any advice you can give!
你可以设置任何应该被预选为select的ngModel
值的ngModel
console.clear();
angular.module('so-answer', [])
.controller('ctrl', ['$scope',
function($scope) {
$scope.options = [1, 2, 3, 4, 5, 6];
$scope.selected = 3;
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="so-answer" ng-controller="ctrl">
<select ng-model="selected" ng-options="opt for opt in options"></select>
</div>
You can try this syntax. Also, you need to use the ng-model that will five you the value you need to select:
<select class="form-control"
ng-model="yourmodel"
ng-options="option for option in allEventData">
</select>
In addition to the answers already posted, I'll add this one. This one demonstrates how to use an array of objects for the select. In this case the events in allEventData are assumed to have a name
and value
property. Adjust to your case accordingly
angular.module("app", [])
.controller("controller", function($scope){
$scope.allEventData = [
{
value: 1,
name: "Event 1"
},
{
value: 2,
name: "Event 2"
},
{
value: 3,
name: "Event 3"
}
]
$scope.selectedEventValue = 3
})
<!DOCTYPE html>
<html ng-app="app" ng-controller="controller">
<head>
<script data-require="angularjs@1.5.7" data-semver="1.5.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<select class="form-control" id="eventSelectMenu" ng-model="selectedEventValue" ng-options="item.value as item.name for item in allEventData">
</select>
<pre>Selected Value: {{selectedEventValue}}</pre>
</body>
</html>
链接地址: http://www.djcxy.com/p/88092.html
上一篇: 用freemarker预选选择字段