angular指令監聽ng-repeat渲染完成后執行自定義事件方法


今天工作中遇到需要用到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>

 

 Demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM