<divng-app="myApp"ng-controller="myCtrl"><p>给 id 一个别名 y.name,显示出来的name值,但实际还是 id 值。</p><selectng-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>
<divng-app="myApp"ng-controller="myCtrl"><selectng-init="selectPerson=persons['caohui']"ng-model="selectPerson"ng-options="x for (x,y) in persons"></select><p>
年龄:{{selectPerson.age}}
</p><p>
性别:{{selectPerson.sex}}
</p><p>
月薪:{{selectPerson.salary}}
</p></div>
732AngularJS Select(选择框)
页面下拉框初始化是空的,设置初始值方法:
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope){
$scope.cars ={
car01 :{brand :"Ford", model :"Mustang", color :"red"},
car02 :{brand :"Fiat", model :"500", color :"white"},
car03 :{brand :"Volvo", model :"XC90", color :"black"}}
$scope.selectedCar = $scope.cars.car02;//设置第2个为初始值;});
735AngularJS Select
下拉框默认的值为 key-value 对中的 value ,也可以用 as 来修改下拉框的值。
也就是 x for (x, y) 相当于是 y as x for (x, y)。
as 前面的为下拉框的值,后面的为下拉框显示的内容。
也可以不使用 key-value 对中的 value 作为下拉框的值, 直接使用对象的属性,代码示例:
<body> <div ng-app="myApp" ng-controller="myCtrl"> <p>使用 ng-options 创建下拉列表,选中的值是一个对象:</p> <select ng-model="selectedSite" ng-options="y.url as x for (x, y) in sites"> </select> <h4>你选择的是: {{selectedSite}}</h4> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.sites = { site01 : {site : "Google", url : "http://www.google.com"}, site02 : {site : "facesoho", url : "https://www.facesoho.com"}, site03 : {site : "Taobao", url : "http://www.taobao.com"} }; $scope.selectedSite = $scope.sites.site02.url; //设置第2个为初始值; }); </script> </body>尝试一下 »
734AngularJS Select(选择框)
给 id 一个别名 y.name,显示出来的 name 值,但实际还是 id 值。
尝试一下 »
733AngularJS Select(选择框)
另外一种设置初始值的方法:
732AngularJS Select(选择框)
页面下拉框初始化是空的,设置初始值方法:
尝试一下 »
731AngularJS Service
controller 有两种写法,讨论一下两种写法的区别:
写法 1:
app.controller('myCtrl', function($scope, $location) { $scope.myUrl = $location.absUrl(); });写法2:
app.controller('myCtrl', ["$scope","$location",function($scope,$location) { $scope.myUrl = $location.absUrl(); }]);两种写法都是对的,但是推荐第二种写法,因为第一种写法在 js 压缩后会出问题,而第二种写法可以完美应对 js 压缩,原因是:js 压缩后,变量名会重命名,故第一种写法会报错。
上面的例子第 2 种写法还可以这样:
app.controller('myCtrl', ["$scope","$location",function(a, b) { a.myUrl = b.absUrl(); }]);