AngularJS. When select have ng-model attribute, ng-selected not working
我试图在我的
问题:使用模型时如何选择
这是我的朋克(
我的代码:
1 2 3 4 5 6 7 8 9 10 | 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"} ]; }]); |
我的模板:
1 2 3 4 5 6 7 8 9 10 11 | <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> |
非常感谢您的帮助!
不要将ngSelected与ngRepeat一起使用。 使用ngOptions:
1 2 3 4 5 6 | <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> |
请勿将
从文档中:
Note:
ngSelected does not interact with theand ngModel 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
查看其他文档:
-
使用
ng-repeat 生成select 选项 -
将select与
ng-options 结合使用并设置默认值
请参阅Stackoverflow:
-
使用
ng-repeat 生成选择选项(带有演示)