ng-options用法详解

前端之家收集整理的这篇文章主要介绍了ng-options用法详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原文地址: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一般有以下用法

对于数组:

  • labelforvalueinarray

  • selectaslabelforvalueinarray

  • labelgroup bygroupforvalueinarray

  • labeldisable whendisableforvalueinarray

  • labelgroup bygroupforvalueinarraytrack bytrackexpr

  • labeldisable whendisableforvalueinarraytrack bytrackexpr

  • labelforvalueinarray| orderBy:orderexprtrack bytrackexpr(for including a filter withtrack by)

  • 对于对象:

  • labelfor (key,value) inobject

  • selectaslabelfor (key,value) inobject

  • labelgroup bygroupfor (key,value) inobject

  • labeldisable whendisablefor (key,value) inobject

  • selectaslabelgroup bygroupfor(key,value) inobject

  • selectaslabeldisable whendisablefor(key,value) inobject

一个简单的例子:

<script>
angular.module('selectExample',[])
.controller('ExampleController',['$scope',function($scope){
$scope.colors=[
{name:'black',shade:'dark'},{name:'white',shade:'light',notAnOption:true},{name:'red',{name:'blue',shade:'dark',{name:'yellow',notAnOption:false}
];
$scope.myColor=$scope.colors[2];//red
}]);
</script>
<divng-controller="ExampleController">
<ul>
<ling-repeat="colorincolors">
<label>Name:<inputng-model="color.name"></label>
<label><inputtype="checkBox"ng-model="color.notAnOption">Disabled?</label>
<buttonng-click="colors.splice($index,1)"aria-label="Remove">X</button>
</li>
<li>
<buttonng-click="colors.push({})">add</button>
</li>
</ul>
<hr/>
<label>Color(nullnotallowed):
<selectng-model="myColor"ng-options="color.nameforcolorincolors"></select>
</label><br/>
<label>Color(nullallowed):
<spanclass="nullable">
<selectng-model="myColor"ng-options="color.nameforcolorincolors">
<optionvalue="">--choosecolor--</option>
</select>
</span></label><br/>

<label>Colorgroupedbyshade:
<selectng-model="myColor"ng-options="color.namegroupbycolor.shadeforcolorincolors">
</select>
</label><br/>

<label>Colorgroupedbyshade,withsomedisabled:
<selectng-model="myColor"
ng-options="color.namegroupbycolor.shadedisablewhencolor.notAnOptionforcolorincolors">
</select>
</label><br/>

Select<buttonng-click="myColor={name:'notinlist',shade:'other'}">bogus</button>.
<br/>
<hr/>
Currentlyselected:{{{selected_color:myColor}}}
<divstyle="border:solid1pxblack;height:20px"
ng-style="{'background-color':myColor.name}">
</div>
</div>
原文链接:https://www.f2er.com/angularjs/149808.html

猜你在找的Angularjs相关文章