1

In my plunk I have an array of integers, that I have attached $scope.$watch to. When I update the array, my $scope.$watch isnt firing a console.log. Why is my console.log not being called?

<!DOCTYPE html>
<html>

  <head>
    <script data-require="[email protected]" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="test" ng-controller="testArray">

    <div ng-repeat="item in MyArray track by $index"> {{item}}</div>
    <button ng-click="add()">testing Add</button>
  </body>

</html>
<script type="text/javascript">
    'use strict';
    var app = angular.module('test', []);

    app.controller('testArray',['$scope',function($scope){

      $scope.MyArray = [1,2,3,4]

      $scope.add = function(){
        $scope.MyArray.push($scope.MyArray.length+1);
      }
    $scope.$watch('MyArray' , function(){
      console.log($scope.MyArray);
    })
    }]);

</script>

2 Answers 2

4

Change your code to

$scope.$watch('MyArray' , function(){
    console.log($scope.MyArray);
}, true)

Looking at the documentation, you will see that the third parameter indicate that the $watch method will use object equality to determine if your array has changed. It means that angular will use the angular.equals method that supports arrays comparison, for example

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

4 Comments

if you set the third parameters to trus it mean that angular will make a deep watch over the object
I decided to accept @pankajParkers answer because of the memory performance of watchCollection over using angular.copy
@RenanLopesFerreira & gh9 Thanks guys. I'd not have added an answer, if you cover the performance related stuff of deep watcher. So rather than do edit your answer.. I did added new answer. :-)
@PankajParkar I didn't know about $watchCollection, so, thank you!
2

You could use $watchCollection, It would be less expensive than the deep watcher by just providing true option in $watch function.

$scope.$watchCollection('MyArray' , function(){
    console.log($scope.MyArray);
})

The $watchCollection() goes one-level deep and performs an additional, shallow reference check of the top level items in the collection.

If you have really big array on which you wanted to keep watch then don't go for $watch with true(deep watcher). For 1000/2000 records, you will feel lag in angular bindings. So preferred approach would be avoid watcher as much as you can OR just go for $watchCollection

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.