2

Every solution posted which refers to detecting when ng-repeat finishes leans on the scope.$last value, like this:

angular.module('fooApp')

    .directive('onLastRepeat', function () {
        return function (scope, element, attrs) {
            if (scope.$last) {
                setTimeout(function () {
                    scope.$emit('onRepeatLast', element, attrs);
                }, 1);
            }
        };
    })

The problem is that this solution only works if you append to the end of the list. If you insert data in the middle, scope.$last will always be false and you have no idea when angularjs has finished renedering your newly bound rows. Does anyone have a solution which work regardless of where ng-repeat renders the data?

example:

html:

<button ng-click="addToList()"></button>
<table>
    <tbody>
        <tr ng-repeat="foo in list" on-last-repeat><td><span>{{foo}}</span></td></tr>
    </tbody>
</table>

controller code:

$scope.addToList = function() {
    $scope.list.splice(1, 0, 4);
}

$scope.list = [1, 2, 3];

if you click the button in an example with the above code $scope.last is false in the directive which is supposed to trigger when rendering is done.

3
  • what do you mean by "If you insert data in the middle"? Commented Oct 9, 2014 at 10:21
  • Can you show a more concrete example of what you mean? Commented Oct 9, 2014 at 10:50
  • sure can, check it out Commented Oct 9, 2014 at 12:04

1 Answer 1

2

Could you use something like this?

angular.module('fooApp')
.directive('onLastRepeat', function () {
    return function (scope, element, attrs) {
        if (scope.$middle) {
            setTimeout(function () {
                scope.$emit('onRepeatMiddle', element, attrs);
            }, 1);
        }


        if (scope.$last) {
            setTimeout(function () {
                scope.$emit('onRepeatLast', element, attrs);
            }, 1);
        }
    };
})
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but the "middle" trigger will fire multiple times instead of just once (given that you add more than one element), so its not semantically identical.
@Marius I'm not able to reproduce that behavior (multiple triggerings). Check out this CodePen: codepen.io/yngvebn/pen/GvABs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.