
ng-options可以接收一个数组或者对象,并对它们进行循环,将内部的内容提供给select标签内部的选项。而select中需要设置默认值,是如何设置呢?其实可以使用ng-model绑定数据myColor,也可以在对应的controller中定义ng-model全局数据$scope.myColor,并为其赋值。或者双向绑定指定ng-model,设置选中的值。
ng-options的表达式格式:
1 | <所选属性> as <标签> for <变量> in <数组>
|
方法一:使用ng-model绑定数据myColor。
1 2 3 4 5 6 | angular.module( 'myApp' , [])
.controller( 'MyController' , [ '$scope' ], function ( $scope ) {
$scope .colors = [ 'black' , 'white' , 'red' , 'blue' , 'yellow' ];
$scope .myColor = $scope .colors[2];
})
|
方法二:在对应的controller中定义ng-model全局数据$scope.myColor,并为其赋值。
1 2 3 | <div ng-controller= "MyController" >
<select ng-model= "myColor" ng-options= "color for color in colors" ></select>
</div>
|
注意:赋值为select的默认值。
方法三:双向绑定指定ng-model,设置选中的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!DOCTYPE html>
<html xmlns= "http://www.w3.org/1999/xhtml" ng-app= "app" >
<head>
<title>select</title>
<script src= "JS/angular.min.js" ></script>
<script>
var app = angular.module( 'app' , []);
app.controller( 'selectController' , function ( $scope ) {
$scope .mycity = '北京' ;
$scope .Cities = [{ id: 1, name: '北京' , group: '中国' }, { id: 2, name: '上海' , group: '中国' }, { id: 3, name: '广州' , group: '中国' }];
});
</script>
</head>
<body>
<div ng-controller= "selectController" >
<select ng-model= "mycity" ng-options= "city.name as city.name group by city.group for city in Cities" ></select>
<h1>欢迎来到{{mycity}}</h1>
</div>
</body>
</html>
|
以上就是小编总结的的三种angularjs ng-options设置默认值额方法,希望能对你有所帮助哦~