原文地址:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/ng-options-usage/
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
一個簡單的例子:
<script> angular.module('selectExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light', notAnOption: true}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark', notAnOption: true}, {name:'yellow', shade:'light', notAnOption: false} ]; $scope.myColor = $scope.colors[2]; // red }]); </script> <div ng-controller="ExampleController"> <ul> <li ng-repeat="color in colors"> <label>Name: <input ng-model="color.name"></label> <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label> <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button> </li> <li> <button ng-click="colors.push({})">add</button> </li> </ul> <hr/> <label>Color (null not allowed): <select ng-model="myColor" ng-options="color.name for color in colors"></select> </label><br/> <label>Color (null allowed): <span class="nullable"> <select ng-model="myColor" ng-options="color.name for color in colors"> <option value="">-- choose color --</option> </select> </span></label><br/> <label>Color grouped by shade: <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> </select> </label><br/> <label>Color grouped by shade, with some disabled: <select ng-model="myColor" ng-options="color.name group by color.shade disable when color.notAnOption for color in colors"> </select> </label><br/> Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>. <br/> <hr/> Currently selected: {{ {selected_color:myColor} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':myColor.name}"> </div> </div>