今天工作中遇到需要用到ng-repeat遍歷渲染完后執行某個操作,angular本身並沒有提供監聽ng-repeat渲染完成的指令,所以需要自己創建自定義指令。
在ng-repeat模板實例內部會暴露出一些特殊屬性$index/$first/$middle/$last/$odd/$even,$index會隨着每次遍歷(從0開始)遞增,當遍歷到最后一個時,$last的值為true,所以可以通過判斷$last的值來監聽ng-repeat的執行狀態,
怎么在遍歷過程中拿到$last的值:自定義指令
var app = angular.module('app',[]); app.directive('repeatFinish',function(){ return { link: function(scope,element,attr){ console.log(scope.$index) if(scope.$last == true){ scope.$eval( attr.repeatFinish ); } } } }) app.controller('appCtrl',function($scope,$element){ $scope.arr = [1,2,3,4,5,6]; $scope.tip = '';
//定義repeat完成后要執行的方法,方法名可自行定義 $scope.repeatDone = function(){ $scope.tip = 'ng-repeat完成,我要開始搞事情了!!!';
//執行自己要執行的事件方法 } });
調用時使用angular調用指令的方法就可以了。
<div ng-repeat="i in arr" repeat-finish="repeatDone();"> <p ng-bind="i"></p> </div>