angularjs – ngOptions导致选项具有错误的值
我正在尝试渲染选择框,但它没有按预期工作 – 选项值不正确.我检查了
manual,根据它的数组语法(在我的情况下,对象数组)是
select as label for value in array 所以这就是我在做的事情: 数据: [{"id":"3","name":"asdasd","code":"asdads","group":"2","cost":"0"},{"id":"4","name":"adrf fg df ","code":"dasfasd","cost":"0"}] 模板: <select ng-model="productToBuy" ng-options="item.id as item.id for item in products"></select> 渲染结果: <select ng-model="productToBuy" ng-options="item.id as item.id for item in products" class="ng-pristine ng-valid"> <option value="0" selected="selected">3</option> <option value="1">4</option> </select> 我们可以看到,选项值不会设置为项目的ID. 当source是数组时,这可能不是正确的语法,但是在尝试这样的时候我得到相同的结果: <select ng-model="productToBuy" ng-options="item.id as item.id for (key,item) in products"></select> 我把这个代码放在jsfiddle.任何帮助表示赞赏. 解决方法
这是ngOptions指令的行为(您看到的输出,其中值是项的索引,而不是您尝试从代码示例传入的id属性). ngOptions将所选选项数据绑定到您在ngModel中指定的变量.然后,您将使用数据绑定变量而不是选项元素本身的“值”.
HTML: <select ng-model="selected" ng-options="item.name for item in items"></select> {{ selected }} JS: $scope.items = [ {"id": "3",{"id": "4","cost":"0"} ]; 在上面的示例中,$scope.selected将表示实际选定的项目.然后,您可以访问任何所选项目的属性:$scope.selected.name,$scope.selected.code …等. 如果您需要使用上面的示例预选项目,则可以执行以下操作: $scope.items = [ {"id": "3","cost":"0"} ]; $scope.selected = $scope.items[1]; // Pre-selected the 2nd item in your array 如果您仍然需要完全控制您的值属性,那么最好使用ng-repeat指令,但请记住,如果这样做,您选择的项目将不会绑定到您的模型. 编辑:注意’选择作为数组中的值的标签’语法: 如果它有用,你的“item.id as item.name for products in products”正在做什么实际上是在ngModel指令中将你的变量设置为你在语法的select部分中指定的值.那么表达式正在做的是将标签设置为item.name,但是将$scope.selected绑定到item.id的值,而不是绑定到项本身的整个实例.因此,如果选择上面示例中的第一项,则$scope.selected将等于“3”.它实际上不会更改选项元素本身的value属性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |