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>
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
解決angular2 獲取到的數(shù)據(jù)無法實時更新的問題
今天小編就為大家分享一篇解決angular2 獲取到的數(shù)據(jù)無法實時更新的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08Angular2中如何使用ngx-translate進行國際化
本篇文章主要介紹了Angular2中使用ngx-translate進行國際化,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05關(guān)于AngularJS中幾種Providers的區(qū)別總結(jié)
這篇文章主要給大家介紹了關(guān)于AngularJS中幾種Providers的區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用AngularJS具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-05-05