Html
数据为对象时绑定使用键值对或.属性
ng-options="x for(x,y) in list"
ng-options="x.属性 for x in list"
给下拉框设置初始值
<div ng-app="myApp" ng-controller="myCtrl">
<!-- ng-repeat 创建 -->
<select>
<option ng-repeat="item in list">{{ item.brand }}</option>
</select>
<!-- ng-options 创建 读取对象中的列并赋初始值-->
<select ng-init="selectedCar=list['car01']" ng-model="selectedCar" ng-options="x.brand for x in list">
</select>
<p>color:{{ selectedCar.color }}</p>
<p>model:{{ selectedCar.model }}</p>
</div>
ng-model中绑定的是选中的值
JS
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
//赋值
$scope.list = {
car01: {
brand: "Ford",
model: "Mustang",
color: "red"
},
car02: {
brand: "Fiat",
model: "500",
color: "white"
},
car03: {
brand: "Volvo",
model: "XC90",
color: "black"
}
}
//设置初始值
// $scope.selectedCar = $scope.list.car01;
});
给对象一个别名 ,显示为name,实际值为id
<div ng-app="myApp" ng-controller="myCtrl">
<p>给 id 一个别名 y.name,显示出来的 name 值,但实际还是 id 值。</p>
<select ng-init="selectPersonid=persons['caohui'].id" ng-model="selectPersonid" ng-options="y.id as y.name for (x,y) in persons">
</select>
<p>
id:{{selectPersonid}}
</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.persons = {
caohui: {
id:1,
age: 27,
name:'a'
},
youlangta: {
id:2,
age: 20,
name:'b'
},
chenyanchan: {
id:3,
age: 24,
name:'c'
}
}
})
</script>
ng-directive自定义指令
<div ng-app="myApp" ng-controller="myCtrl">
<runoob-directive></runoob-directive>
</div>
<script>
var app=angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
})
app.directive("runoobDirective", function () {
return {
template: "<h2>自定义指令!</h2>"
};
});
</script>
var app=angular.module('myApp',[]);
在模块定义中 [] 参数用于定义模块的依赖关系。
中括号[]表示该模块没有依赖,如果有依赖的话会在中括号写上依赖的模块名字。