Calling a function when ng-repeat has finished

前端 未结 10 1672
面向向阳花
面向向阳花 2020-11-22 02:28

What I am trying to implement is basically a \"on ng repeat finished rendering\" handler. I am able to detect when it is done but I can\'t figure out how to trigger a functi

10条回答
  •  青春惊慌失措
    2020-11-22 03:04

    var module = angular.module('testApp', [])
        .directive('onFinishRender', function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function () {
                        scope.$emit(attr.onFinishRender);
                    });
                }
            }
        }
    });
    

    Notice that I didn't use .ready() but rather wrapped it in a $timeout. $timeout makes sure it's executed when the ng-repeated elements have REALLY finished rendering (because the $timeout will execute at the end of the current digest cycle -- and it will also call $apply internally, unlike setTimeout). So after the ng-repeat has finished, we use $emit to emit an event to outer scopes (sibling and parent scopes).

    And then in your controller, you can catch it with $on:

    $scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
        //you also get the actual event object
        //do stuff, execute functions -- whatever...
    });
    

    With html that looks something like this:

    {{item.name}}}

提交回复
热议问题