问题
I\'m trying to set ng-selected
in my option
element, selected
attribute is set to true
, but option
not selected, When I remove ng-model
from select
all become working.
The question: How to make option
selected, when I\'m using the model?
Here is my plunker (selected
not working here)
My code:
var app = angular.module(\"plunker\", []);
app.controller(\"TestController\", [\"$scope\", function($scope) {
$scope.test = 1;
$scope.array = [
{\"id\": 1, \"name\": \"first\"},
{\"id\": 2, \"name\": \"second\"},
{\"id\": 3, \"name\": \"third\"}
];
}]);
My template:
<body ng-controller=\"TestController\">
Selected item must be {{ array[test-1].name }}
<select ng-model=\"myModel\">
<option value=\"\">Choose item..</option>
<option ng-repeat=\"item in array\"
ng-value=\"item.id\"
ng-selected=\"item.id == test\">
{{ item.name }} ({{item.id == test}})
</option>
</select>
</body>
Thanks a lot for any help!
回答1:
Don't use ngSelected with ngRepeat. Go with ngOptions:
<body ng-controller="TestController">
Selected item must be {{ array[test-1].name }}
<select ng-model="myModel" ng-options="item.id as item.name for item in array">
<option value="">Choose item..</option>
</select>
</body>
回答2:
Don't use ngSelected
with ngModel
From the Docs:
Note:
ngSelected
does not interact with the<select>
andngModel
directives, it only sets the selected attribute on the element. If you are usingngModel
on the select, you should not usengSelected
on the options, asngModel
will set the select value and selected options.— AngularJS ng-selected API Reference
See additional Docs:
- Using ng-repeat to generate select options
- Using select with ng-options and setting a default value
See Stackoverflow:
- Using ng-repeat to generate select options (with Demo)
来源:https://stackoverflow.com/questions/34996714/angularjs-when-select-have-ng-model-attribute-ng-selected-not-working