AngularJS中使用ng-repeat的index問題
AngularJS使用ng-repeat的index
AngularJS中的ng-repeat中,隱含的index,可以使用$index來訪問,也可以自己指定index對應的變量名。
使用隱含的index變量
隱含的index變量名是index,可以使用$index來訪問。
// 定義module和controller
var site = angular.module('application.site', []);
site.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.users = [
{name:"xialei",posts:["post一","post二","post三"]},
{name:"zhangsan",posts:["post四","post五"]}
];
}]);下面在html頁面內(nèi)使用controller和定義的collection對象。
<div ng-controller="MainController">
<dl ng-repeat="user in users">
<dt ng-init="p_index=$index">Name:{{ user.name }}</dt>
</dl>
</div>這里使用了$index,這是AngularJS提供的隱含的collection對象的index變量量。
指定index變量名
在ng-repeat中可以自己指定index的變量名稱,并在隨后使用。
比如下面代碼中,定義了times的index變量名稱timeIndex (為tr 元素), 為days的遍歷操作,定義了dayIndex的索引變量。
<tr data-ng-repeat="(timeIndex, time) in times">
<td style="text-align: center; width: 12.5%;" data-ng-style="doGetTimeColumnStyle($index)">{{time}}</td>
<td data-ng-repeat="(dayIndex, day) in days"
data-ng-click="selectDatetimeSlot(dayIndex, day, timeIndex, time)">
<button class="popupWindow"
data-ng-if="datetimeSlots[dayIndex][timeIndex].status && datetimeSlots[dayIndex][timeIndex].status != 'AVAILABLE' && datetimeSlots[dayIndex][timeIndex].status != 'EXPIRED' &&
datetimeSlots[dayIndex][timeIndex].mode != 'ONE_V_MANY'"
data-ng-class="datetimeSlots[dayIndex][timeIndex].displayStatus | lowercase"
data-placement="{{doGetTimeColumnPopOverPlacement(dayIndex, timeIndex)}}" data-animation="am-flip-x"
data-trigger="focus" data-bs-popover
data-template="partials/timeSlotPopover.html">
{{datetimeSlots[dayIndex][timeIndex].displayStatus}} {{datetimeSlots[dayIndex][timeIndex].stdName}}
</button>
ps:
$index是angular 內(nèi)針對ng-repeat提供的隱含index變量名稱,如果在ng-repeat嵌套使用時,index名稱會發(fā)生沖突及覆蓋。這是也應該使用自定義的變量名。
下面例子中父級的index使用ng-init,定義了p_index來指定為parent index。
<div ng-controller="MainController">
<dl ng-repeat="user in users">
<dt ng-init="p_index=$index">Name:{{ user.name }}</dt>
<dd ng-repeat="p in user.posts">Parent index:{{ p_index }} - {{ p }}
self Index:{{ $index }}
</dd>
</dl>
</div>
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
AngularJS自定義插件實現(xiàn)網(wǎng)站用戶引導功能示例
這篇文章主要介紹了AngularJS自定義插件實現(xiàn)網(wǎng)站用戶引導功能,結合實例形式分析了AngularJS自定義插件的實現(xiàn)步驟與相關功能技巧,需要的朋友可以參考下2016-11-11
詳解AngularJS1.x學習directive 中‘& ’‘=’ ‘@’符號的區(qū)別使用
這篇文章主要介紹了詳解AngularJS1.x學習directive 中‘& ’‘=’ ‘@’符號的區(qū)別使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-08-08
Angular.js中用ng-repeat-start實現(xiàn)自定義顯示
大家都知道Angular.js可以用ng-repeat來顯示列表數(shù)據(jù),可是如果想要自定義顯示數(shù)據(jù)列表的話ng-repeat就實現(xiàn)不了了,這個時候可以利用ng-repeat-start 和 ng-repeat-end來實現(xiàn),下面通過本文來詳細看看實現(xiàn)的方法吧。2016-10-10
angularjs 的數(shù)據(jù)綁定實現(xiàn)原理
本篇文章主要介紹了angularjs 的數(shù)據(jù)綁定實現(xiàn)原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
深究AngularJS如何獲取input的焦點(自定義指令)
本篇文章主要介紹了AngularJS如何獲取input的焦點(自定義指令),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06

