关于ng-option
Posted Dear 丶Lord
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于ng-option相关的知识,希望对你有一定的参考价值。
ng-options属性可以在表达式中使用数组或对象来自动生成一个select中的option列表。ng-options与ng-repeat很相似,很多时候可以用ng-repeat来代替ng-options。但是ng-options提供了一些好处,例如减少内存提高速度,以及提供选择框的选项来让用户选择。当select中一个选项被选择,该选项将会被绑定到ng-model。如果你想设一个默认值,可以像这样:$scope.selected = $scope.collection[3]。
之前一直在用ng-repeat就见到过track by,没有去了解它的用法,这次了解了一下。track by主要是防止值有重复,angularjs会报错。因为angularjs需要一个唯一值来与生成的dom绑定,以方便追踪数据。例如:items=[“a”,“a”,“b”],这样ng-repeat=“item in items”就会出错,而用ng-repeat=“(key,value) in items track by key”就不会出现错误了。
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
一个具体工作中的例子:
<div class="input-field col s6" ng-class="{ ‘has-error‘:change_newStorage_carForm.arrive_city.$invalid&&submitted }"> <select material-select watch id="arrive_city" name="arrive_city" ng-change="get_received(arrive_city.id)" ng-options="arrive_city.city_name for arrive_city in get_city" ng-model="arrive_city" required> <option value="" disabled selected>请选择</option> </select>
<label for="arrive_city">目的地城市</label>
</div>
// 城市 _basic.get($host.api_url+"/city").then(function (data) { if(data.success==true){ $scope.get_city=data.result; } }); 例如: [ {id: 100, city_name: "大连", city_status: 1, created_on: "2017-06-29T06:20:25.000Z"}, {id: 101, city_name: "沈阳", city_status: 1, created_on: "2017-07-05T06:45:17.000Z"}, {id: 102, city_name: "鞍山", city_status: 1, created_on: "2017-07-05T07:52:20.000Z"}, {id: 103, city_name: "铁岭", city_status: 1, created_on: "2017-07-06T08:43:20.000Z"} ]
下拉选择的时候,
ng-model中的
arrive_city是一个选中的对象。
{id: 100, city_name: "大连", city_status: 1, created_on: "2017-06-29T06:20:25.000Z"}
ng-options="arrive_city.city_name for arrive_city in get_city",中显示city.name的字段,value则是一个对象:{id: 100, city_name: "大连", city_status: 1, created_on: "2017-06-29T06:20:25.000Z"}
如果后台返回数据中有个默认的选中值,取出默认值的含有id的字段,假如100,
则先循环遍历
$scope.get_city中的数据,
$scope.get_city.forEach(function (val) {
if(val.id==100){
$scope.select_city_start=val;
}
});
通过id 来确认默认选中的那个对象,然后把这个选中的对象赋值给ng-model
$scope.start_city= $scope.select_city_start;
以上是关于关于ng-option的主要内容,如果未能解决你的问题,请参考以下文章