1. 程式人生 > >angularJS中的ng-repeat指令!

angularJS中的ng-repeat指令!

註意 func control wid 案例 del fis cnblogs ext

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">red</option>
    <option value="orange">orange</option>
    <option value="yellow">yellow</option>
</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>

angularJS中的ng-repeat指令!