刚刚接触AngularJs,记录一下ng-options的使用。
1、构造key-value数据
$scope.types = [
{id:"1",type:"AA"},
{id:"2",type:"BB"},
{id:"3",type:"CC"}
];
2、绑定
<select ng-model="selectType" ng-options="t.id as t.type for t in types">
<option values=""></option>
</select>
ng-options="t.id as t.type for t in types" 代表生成的option标签 <option value="t.id"> t.type</option>
在使用当中需要下拉框默认显示 BB 这条数据,开始以为 $scope.selectType=2 就可以让下拉框默认显示BB,结果失败了。
查资料发现:
ng-model 是通过引用而不是通过值来控制model的。
上述例子中,想预选中BB标签,然后将id=2复制给model,只是将数值传给了model,并不能得到预期的效果。
需要将BB的引用传给model。 $scope.selectType=$scope.types[1].id
此外还需到此问题:
html标签:
<select class="form-control" ng-model="aa.b" ng-options="zp.id as zp.name for zp in zps">
</select>
数据:
$scope.zps=[
{id:"1",name:"aaaa"},
{id:"2",name:"bbbb"},
{id:"3",name:"bbbc"}
];
需要给select标签设置默认选项,指令如下:
$scope.aa={b:"1"}; 下拉框将默认显示为“aaaa”