1

I'm attempting to trigger a $watch after a timeout in angular:

My Controller

.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.chickens = ["Jim", "Joe", "Fred"];
    $scope.chickens.push("Steve");

    setTimeout(function () {
        $scope.chickens.push("Larry");
        $scope.$apply();
    }, 500);
}])

Then the $watch is wired up in my directive's link function:

My Directive Link

link: function (scope, element, attrs) {
    scope.$watch('chickens', function (newChickens, oldChickens) {
        $(element).html('');
        newChickens.forEach(function (chicken) {
            $(element).append($('<li/>', {
                'text': chicken
            }));
        });
    });
}

The $watch only seems to fire once with the first four elements, it never fires after the fifth is added. I tried adding the $scope.$apply() there to apply the changes. Doesn't seem to be working.

Here's the Fiddle for the example. I'd appreciate any help in the situation. Thanks!

1 Answer 1

2

Change your directive like so:

link: function (scope, element, attrs) {
    scope.$watch('chickens', function (newChickens, oldChickens) {
        $(element).html('');
        newChickens.forEach(function (chicken) {
            $(element).append($('<li/>', {
                'text': chicken
            }));
        });
    }, true);
}

The 3rd parameter (objectEquality) will make the watch check the whole contents of the array. Specifically it will use angular.equals to check the equality of the new and old array:

https://docs.angularjs.org/api/ng/function/angular.equals

Sign up to request clarification or add additional context in comments.

2 Comments

Ah there it is! Makes sense. Wouldn't want to do that all the time for performance purposes. Thank you.
Yeah, it will have a negative impact on performance. Especially if the array is large.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.