再举例:
1 <body ng-app="app" ng-controller="ctrl"> 2 <select ng-model="site3"> 3 <option ng-repeat="item in options">{{item}}</option> 4 </select> 5 6 <pre>{{site3}}</pre> 7 </body> 8 <script type="text/javascript" src="js/angular.js"></script> 9 <script type="text/javascript"> 10 angular.module("app",[]) 11 .controller("ctrl",function($scope){ 12 $scope.options = ["张三","李四","王二麻子","赵六","李胖"]; 13 </script>结果:
再再举个栗子:
<body ng-app="app" ng-controller="ctrl"> <select ng-model="site2"> <option ng-repeat="item in sites" value="{{item.url}}">{{item.site}}</option> </select> <pre>{{site2}}</pre> </body> <script type="text/javascript" src="js/angular.js"></script> <script type="text/javascript"> angular.module("app",[]) .controller("ctrl",function($scope){ $scope.sites = [ {site : "Google", url : ""}, {site : "Runoob", url : ""}, {site : "Taobao", url : ""} ]; }) </script>结果:
二、以对象作为数据源
1、 (key,value) 第一项表示对象的键,第二项表示对象的值;
2、 option的value,永远都是对象的值!
3、 option显示出的内容(<option></option>标签中的文字)是由...for 决定的!也就是说 for前面是什么,option标签中就是什么。
再再再举个栗子!!
<body ng-app="app" ng-controller="ctrl"> <select ng-model="site4" ng-options="key for (key,value) in sitess"></select> <pre>{{site4}}</pre> </body> <script type="text/javascript" src="js/angular.js"></script> <script type="text/javascript"> angular.module("app",[]) .controller("ctrl",function($scope){ $scope.sitess = { site01 : "Google", site02 : "Runoob", site03 : "Taobao" }; }) </script>结果:
从上面两个例子中可以发现,在取到数组或对象中每个值得时候,使用了两种方式:ng-options 和 ng-repeat;
那么,我们来分析一下两者之间的不同:
1、ng-options使用时,是将指令添加在select上;
ng-repeat使用时,是将指令添加到option上;
2、 ng-options使用时,必须同步给select标签绑定ng-model;
ng-repeat使用时,不一定需要绑定ng-model
3、 ng-options使用时,我们只需要关心for前面的部分,即option标签中显示的文字;而option的value会自动分配,不由我们决定。 (使用数组作为数据源是,value就是数组的每一项;使用对象作为数据源是,value永远都是对象的值)
ng-repeat使用,除了要指定option标签中显示的文字,还需要手动指定value中的内容,如果没有指定则默认没有value;
2.2 AngularJS中的表格其实表格的制作和上述的select是一样的方法,只要明白如何取值,那么表格就只是样式的问题了。
疯狂举栗子:
1 <body ng-app="app" ng-controller="ctrl"> 2 <table width="400" border="1"> 3 <tr> 4 <th>序号</th> 5 <th>姓名</th> 6 </tr> 7 <tr ng-repeat="item in options"> 8 9 <!--ng-repeat遍历是,$index 表示当前的行索引!--> 10 11 <td>{{$index + 1}}</td> 12 <td>{{item}}</td> 13 </tr> 14 </table> 15 16 17 </body> 18 19 <script type="text/javascript" src="js/angular.js"></script> 20 <script type="text/javascript"> 21 angular.module("app",[]) 22 .controller("ctrl",function($scope){ 23 $scope.options = ["张三","李四","王二麻子","赵六","李胖"]; 24 </script>结果:
三、AngularJS中的DOM与事件
接下来给大家介绍一些AngularJS中的dom事件,在AngularJS中,大部分的dom事件都是通过其指令来实现;
3.1 AngularJS中的DOM1、ng-disabled="true/false";
传入true表示禁用,传入false表示可用;
2、ng-hide:是否隐藏;true表示隐藏,false表示不隐藏
3、ng-show:是否显示;true表示显示,false表示不显示
所以因为我们通常遇见的是true表示通用,所以,在事件的前面加上“!”;这只是个人习惯问题,没有规定必须;