1

I want to watch an array changes inside Angular controller and update HTML view.

this is my controller:

app.controller("timelineCtrl", function ($scope) {
    $scope.arr=[];
         .
         .
         .
}

this is my directive:

app.directive('helloWorld', function() {
    return {
        restrict: 'AE',
        replace: true,
        template: '<div> Hello {{arrayItem}} </div>',

        link: function ($scope, element, attrs) {

            $scope.$watch($scope.arr, function(newValues, oldValues) {
                $scope.arrayItem = newValues;
            });

        }
    };
});

I add some new values to array via button click but my $watch doesn't work. How can i overcome this?

1
  • @vinayakj why wouldn't it be? Commented Jul 19, 2015 at 20:19

2 Answers 2

1

Currently your watch is not firing because the $scope.arr variable contains the same reference - a reference to the same array as initially, only the values contained in this array have now changed. (This is because arrays in javascript are passed by reference only, as opposed to primitives which are always copied)

If you want watch to go "deeper" than just checking this reference, and look for changes in the object's contents too, you can add a third, boolean param with a true value, as such:

$scope.$watch(
   '$scope.arr', //expression to watch - can also be a function returning a value
   function(newValues, oldValues) { //function to run on change
     $scope.arrayItem = newValues;
   },
   true //deep watch mode?
);

Do note that watching "deep" can be very expensive, as it will check every last property of every embedded object. If you just want to watch whether an element was removed or added to an array, you can use $watchCollection, which only watches shallow, 1 level down, and has much better performance.

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

Comments

0

You should place deep watch of array by adding true after the function, that will do deep watch on the variable, any of the element changed inside watch will fire function

Markup

<hello-world arr="arr" ></hello-world>

Code

$scope.$watch(attrs.arr, function(newValues, oldValues) {
     $scope.arrayItem = newValues;
}, true);

Comments

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.