原文地址:http://www.ncloud.hk/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/ng-options-usage/angularjs
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」就不會出現錯誤了。dom
ng-options通常有如下用法:spa
對於數組:orm
一個簡單的例子:對象
<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>