angularJS中的ng-repeat指令!

ng-repeat 指令:

ng-repeat 指令用来遍历一个数组重复创建当前元素;

<ul ng-app="myApp" ng-controller="myAppController"><li ng-repeat="item in userNames track by $index">{{$index}}:{{item}}li>
ul>
<script type="text/javascript">
var myApp = angular.module("myApp",[]);
myApp.controller('myAppController',['$scope',function($scope){$scope.userNames = {"id":1,"name":"小三","age":"20"};
}]);
script>

案例二:

<ul ng-app="myApp" ng-controller="myAppController"><li ng-repeat="item in datashuju track by $index" data-id="{{item.id}}">{{$index}}:{{item.name}}的年龄是{{item.age}}li>
ul>
<script type="text/javascript">
var myApp = angular.module("myApp",[]);
myApp.controller('myAppController',['$scope',function($scope){$scope.datashuju = [];for(var i=0; i<10; ++i){//常见写法,不写 i 
        $scope.datashuju[$scope.datashuju.length] = {id:i,name:'赵小黑'+i,age:20+i};};
}]);
script>

在这个例子中,Models中有:

$id:10

item:Objet

$index:1

$first:false

$last:false

$middle:true

$even:false

$odd:true

例如:$first 和 $last的简单使用:

<ul ng-app="myApp" ng-controller="myAppController"><li ng-repeat="item in datashuju track by $index" data-id="{{item.id}}">{{$first?'开始':''}}{{$index}}:{{item.name}}的年龄是{{item.age}}{{$last?'结束':''}}li>
ul>

ng-repeat结合ng-class实现各行换色

ng-class:会根据当前设置对象的属性和属性值决定是否添加特定的类名:

<ul ng-app="myApp" ng-controller="myAppController"><li ng-repeat="item in datashuju track by $index" ng-class="{red:true}" data-id="{{item.id}}">{{$first?'开始':''}}{{$index}}:{{item.name}}的年龄是{{item.age}}{{$last?'结束':''}}li>
ul>

实现各行换色:(注意这里用到的是一个大括号)

<ul ng-app="myApp" ng-controller="myAppController"><li ng-repeat="item in datashuju track by $index" ng-class="{red:$even,green:$odd}" data-id="{{item.id}}">{{$first?'开始':''}}{{$index}}:{{item.name}}的年龄是{{item.age}}{{$last?'结束':''}}li>
ul>

 

ng-class拓展:结合双向数据绑定,实现选择颜色替换背景:

<style type="text/css">
.red{background:red}
.orange{background: orange;}
.yellow{background: yellow;}
#box{width: 200px; height: 200px;}
style>
<div ng-app>
<select ng-model='color'><option value="red">redoption><option value="orange">orangeoption><option value="yellow">yellowoption>
select>
<div id="box" ng-class="color">div>
div>

ng-repeat 解决重复项,使用 trak by $index

 结合 startsWith()做一个筛选:

<ul ng-app="myApp" ng-controller="myAppController"><li ng-repeat="item in datashuju track by $index" ng-class="{red:item.startsWith('张')}">{{item}}li>
ul>
<script type="text/javascript">
var myApp = angular.module("myApp",[]);
myApp.controller('myAppController',['$scope',function($scope){$scope.datashuju = ['刘备','关羽','张飞','关兴','张三'];
}]);
script>

结合双向数据绑定使用:

<ul ng-app="myApp" ng-controller="myAppController"><input type="text" ng-model="fistName"><li ng-repeat="item in datashuju track by $index" ng-class="{red:item.startsWith(fistName)}">{{item}}li>
ul>

 

转载于:https://www.cnblogs.com/e0yu/p/7221470.html


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部