angularJS
ng-repeat指令
作用:遍历集合-通过in的方式遍历每一项
如:
ng-app:初始化angularjs库的指令
ng-controller:调用控制器把数据、视图链接在一起
ng-click:点击操作事件的指令
ng-model:将视图中的数据与JS中的数据进行绑定
代码示例:
var m=angular.module('myApp',[]);
m.controller('Aaa',['$scope',function($scope){
$scope.dataList = [
'aaaaaa','bbbbbb','cccccc'
];
}]);
<div ng-controller="Aaa">
<ul>
<li ng-repeat="data in dataList">{{data}}</li><!--用data遍历数据同时自动生成列表并展现在页面中,data是指数据中的值-->
</ul>
</div>
页面展示示例:
- aaaaaa
- bbbbbb
- cccccc
示例:表格的操作(可点击姓名、年龄进行排序,点击一次从大到小,两次从大到小。同时可进行内容搜索并输出)
<script>
var m=angular.module('myApp',[]);
m.controller('Aaa',['$scope','$filter',function($scope,$filter){
var oriArr = [
{name:"Tom",age:"20"},
{name:"Lucy",age:"18"},
{name:"Lily",age:"32"},
{name:"Jack",age:"40"}
];
$scope.dataList = oriArr;
$scope.fnSort = function(arg){
arguments.callee['fnSort'+arg]=!arguments.callee['fnSort'+arg];//挂载arg充当开关同时为了防止与系统自带的属性相冲突故在前加上‘fnSort’
$scope.dataList = $filter('orderBy')($scope.dataList,arg,arguments.callee['fnSort'+arg]);
}
$scope.fnFilter = function(){
$scope.dataList = $filter('filter')(oriArr,$scope.filterValue);
}
}]);
</script>
<div ng-controller="Aaa">
<input type="text" ng-model="filterValue"/><input type="button" ng-click="fnFilter()" value="搜索" />
<table border="1">
<tr>
<th ng-click="fnSort('name')">姓名</th>
<th ng-click="fnSort('age')">年龄</th>
</tr>
<tr ng-repeat="data in dataList">
<td>{{data.name}}</td>
<td>{{data.age}}</td>
</tr>
</table>
</div>
页面展示示例:
表格全部输出:
表格按照年龄从小到大排序:
根据搜索内容查询表格内容:
ng-repeat的扩展部分
$index:索引号
代码示例:
<script>
var m=angular.module('myApp',[]);
m.controller('Aaa',['$scope',function($scope){
$scope.dataList = [
'aaaaaa','bbbbbb','cccccc','dddddd','eeeeee'
]
}])
</script>
<body>
<div ng-controller="Aaa">
<ul>
<li ng-repeat="data in dataList">{{$index}}</li>
</ul>
</div>
</body>
页面展示示例:
$first:数据的第一项返回真true,其它项则均返回false
代码示例:
<li ng-repeat="data in dataList">{{$first}}</li>
页面展示示例:
$middle:除了首项、尾项返回false,其余均返回true,类似与first
$last:数据的最后一项返回真true,其它项则均返回false
$even:数据的奇数行返回true,偶数行返回false
$odd:数据的偶数行返回true,奇数行返回false
ng-repeat-start:在对多个标签进行循环时,放在循环的第一个标签,使用方法与ng-repeat相同,同时可将数据进行链接并输出。
ng-repeat-end:在对多个标签进行循环时,放在循环的最后一个标签,使用方法与ng-repeat相同,同时可将数据进行链接并输出。
示例(隔行变色):
代码示例:
<style type="text/css">
.active1 { background:red; }
.active2 {background: blue;}
</style>
<script>
var m=angular.module('myApp',[]);
m.controller('Aaa',['$scope',function($scope){
$scope.dataList = [
'aaaaaa','bbbbbb','cccccc','dddddd','eeeeee'
]
}])
</script>
<body>
<div ng-controller="Aaa">
<ul>
<li class="{{$even?'active1':'active2'}}" ng-repeat="data in dataList">{{data}}</li>
</ul>
</div>
</body>
页面结果展示: