AngularJS学习之Select(选择框)

1.AngularJS可以使用数组或对象创建一个下拉列表选项;

2.在AngularJS中我们可以使用ng-option指令创建一个下拉列表;列表项通过对象和数组循环输出:

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="selectedName" ng-options="x for x in names"></select>

</div>

<script>

var app=angular.module('myApp',[]);

app.controller('myCtrl',function($scope){

  $scope.names=["Google","Runoob","Taobao"];

});

</script>

3.ng-options与ng-repeat:也可以使用ng-repeat指令创建下拉列表:

<select>

  <option ng-repeat="x in names">{{x}}</option>

</select>

**ng-repeat指令是通过数组来循环HTML代码来创建下拉列表,但ng-options指令更适合创建下拉列表:使用ng-options的选项的一个对象, ng-repeat是一个字符串;

4.比较ng-repeat和ng-options

**使用以下对象:

$scope.sites=[

  {site:"Google",url:"http://www.google.com"},

  {site:"Runoob",url:"http://www.runoob.com"},

  {site:"Taobao",url:"http://www.taobao.com"}

];

**ng-repeat:

<select ng-model="selectedSite">

<option ng-repeat="x in sites" value="{{x.url}}">{{x.site}}</option>

</select>

<h1>你的选择是:{{slectedSite}}</h1>

**使用ng-options:

<select ng-model="selectedSite" ng-options="x.site for x in sites"></select>

<h1>你的选择是:{{selectedSite.site}}</h1>

<p>网址是:{{selectedSite.url}}</p>

5.数据源为对象:前边使用数组作为数据源,以下将数据对象作为数据源;

$scope.sites=[

  site01:"Google",

  site02:"Runoob",

  site03:"Taobao"

];

**ng-options使用对象有很大不同:使用对象作为数据源,x为键(key),y为值(value):

<select ng-model="selectedSite" ng-options="x for (x,y) in sites"></select>

<h1>你选择的值是:{{selectedSite}}</h1>

**你选择的值为在key-value对中的value;value在key-value对中也可以是个对象:

 $scope.cars={

car01:{brand:"Ford",model:"Mustang",color:"red"},

car02:{brand:"Fiat",model:"500",color:"White"},

car03:{brand:"Volvo",model:"X90",color:"black"}

};

**在下拉菜单中也可以不使用key-value对中的key,直接使用对象的属性:

<select ng-model="selectedCar" ng-options="y.brand for (x,y) in cars"></select>

原文地址:https://www.cnblogs.com/hqutcy/p/6075849.html