0

I need to call a function everytime ng-repeat has finished rendering a view. A simple solution for when ng-repeat gets rendered for the first time i came across is to use ng-init="$last ? function() : angular.noop where 'function' is the function to be called.

Likewise, one could write a custom directive as e.g. in ng-repeat finish event However, so far i have been unsuccessful to find a solution that also works when i have a dynamic ng-repeat

e.g. when items are added or deleted in the middle or when filtered as $last will be false in these cases. One could always add and delete a dummy entry at the end of the list, but this seems not to be a proper solution.

Any suggestions are welcome. Thanks.

Community
  • 1
  • 1
Fluffy
  • 217
  • 1
  • 2
  • 9
  • Put whatever you are repeating inside a directive and your logic inside the directive's controllers constructor – JMK Dec 13 '16 at 09:48

1 Answers1

0

Following JMK's advise (thanks for that) I did the following which seems to work but looks a bit naive --- so any suggestions re improvement are welcome. The directive calls two different functions at the start and at the end of the rendering.

HTML

<div ng-repeat="item in itemsArray" on-finish-render="{items: itemsArray}">
  {{item}}
</div>

JS

    .directive("onFinishRender", ["$parse", "$timeout", function ($parse, $timeout) {    
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                var model = $parse(attr.onFinishRender);
                scope.$watch(model, function (newValue, oldValue) {                         
                    if (scope.$index === 0) {
                        //At the start do stuff 
                    }
                    if (scope.$index === newValue.items.length - 1) {
                        //At the end do some other stuff
                    }
                }, true);
            }
        };
    }]);
Fluffy
  • 217
  • 1
  • 2
  • 9