AngularJS Select(选择框)使用详解
1、Select概述
AngularJS中可以使用ng-option指令来创建一个下拉列表,列表项通过对象和数组循环输出
<divng-app="myApp"ng-controller="myCtrl"> <selectng-model="selectedName"ng-options="xforxinnames"> </select> </div> <script> varapp=angular.module('myApp',[]); app.controller('myCtrl',function($scope){ $scope.names=["Google","Runoob","Taobao"]; }); </script>
2、数据源为对象
选择的值为在key-value对中的key:
<divng-app="myApp"ng-controller="myCtrl"> <p>选择一辆车:</p> <selectng-model="selectedCar"ng-options="xfor(x,y)incars"> </select> <h1>你选择的是:{{selectedCar.brand}}</h1> <h2>模型:{{selectedCar.model}}</h2> <h3>颜色:{{selectedCar.color}}</h3> <p>注意选中的值是一个对象。</p> </div> <script> varapp=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"} } }); </script>
选择的值为在key-value对中的value对象一个属性:
<divng-app="myApp"ng-controller="myCtrl"> <p>选择一辆车:</p> <selectng-model="selectedCar"ng-options="y.brandfor(x,y)incars"> </select> <p>你选择的是:{{selectedCar.brand}}</p> <p>型号为:{{selectedCar.model}}</p> <p>颜色为:{{selectedCar.color}}</p> <p>下拉列表中的选项也可以是对象的属性。</p> </div> <script> varapp=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"} } }); </script>
3、ng-options与ng-repeat
也可以使用ng-repeat指令来创建下拉列表。
ng-repeat指令是通过数组来循环HTML代码来创建下拉列表,但ng-options指令更适合创建下拉列表,它有以下优势:
使用ng-options的选项的一个对象,ng-repeat是一个字符串。
1)ng-repeat有局限性,选择的值是一个字符串:
<divng-app="myApp"ng-controller="myCtrl"> <p>选择网站:</p> <selectng-model="selectedSite"> <optionng-repeat="xinsites"value="{{x.url}}">{{x.site}}</option> </select> <h1>你选择的是:{{selectedSite}}</h1> </div> <script> varapp=angular.module('myApp',[]); app.controller('myCtrl',function($scope){ $scope.sites=[ {site:"Google",url:"http://www.google.com"}, {site:"Runoob",url:"http://www.runoob.com"}, {site:"Taobao",url:"http://www.taobao.com"} ]; }); </script>
2)使用ng-options指令,选择的值是一个对象:
<divng-app="myApp"ng-controller="myCtrl"> <p>选择网站:</p> <selectng-model="selectedSite"ng-options="x.siteforxinsites"> </select> <h1>你选择的是:{{selectedSite.site}}</h1> <p>网址为:{{selectedSite.url}}</p> </div> <script> varapp=angular.module('myApp',[]); app.controller('myCtrl',function($scope){ $scope.sites=[ {site:"Google",url:"http://www.google.com"}, {site:"Runoob",url:"http://www.runoob.com"}, {site:"Taobao",url:"http://www.taobao.com"} ]; }); </script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。