ng-options一般有以下用法及其详解
数组:
- label for value in array
- select as label for value in array
- label group by group for value in array
- label disable when disable for value in array
- label group by group for value in array track by trackexpr
- label disable when disable for value in array track by trackexpr
- label for value in array | orderBy:orderexpr track by trackexpr(for including a filter with track by)
对象:
- label for (key , value) in object
- select as label for (key ,value) in object
- label group by group for (key,value) in object
- label disable when disable for (key, value) in object
- select as label group by group for(key, value) in object
- select as label disable when disable for (key, value) in object
选中:
ng-options的选中方式是根据ng-model而决定的,假如我们的对象是:
[{“value”:0,”name”:”否”},{“value”:1,”name”:”是”}]
那么ng-model对应的就是:
{“value”:0,”name”:”否”} 或者是 {“value”:1,”name”:”是”} 对象。
一个例子:
//The html code. <select class="form-control" ng-model="selected" ng-options="n.name for (i,n) in defaultContent" ng-change="change(selected)"></select>
//and the js code.
.controller("testController",function($scope){ /** * selected value. * @type {string} */ $scope.content = "0"; /** * select options object. */ $scope.defaultContent = JSON.parse('[{"value":0,"name":"否"},{"value":1,"name":"是"}]'); /** * foreach defaultContent and found the selected object. */ for(i in $scope.defaultContent){ /** * if defaultContent[i].value equals content,than the selected object is defaultContent[i]. */ if($scope.defaultContent[i].value == parseInt($scope.content)){ $scope.selected = $scope.defaultContent[i]; break; } } $scope.change = function(obj){ log(obj) } })
- defaultContent是我们默认的下拉选择框的对象数组。
- content是下拉选择框选中value的值
- 经过遍历数组,找出选中值的对应对象复制给新申明的选中对象selected。
- html代码ng-model赋值selected就可以了。
近期评论