1

I have an array with boolean values and what I need to do is try to use the $watch function in order to show a message when some change happens in the array.

As you can see in this code the array changes its values but the $watch function doesn't work. Any idea?

View

<div data-ng-repeat="catA in categoryA">
    <b><input type="checkbox" checked="checked" ng-model="arrayCategoryA[$index]"/>{{catA.name}}</b>
</div>

Controller

app.controller("controllerApp", function($scope, $http, $filter){

  $scope.arrayCategoryA = [];

  $scope.$watchCollection($scope.arrayCategoryA, function(newVal, oldVal){
    console.log("something changed");
  }, true);

  $http.get("categoryA.json").success(function(data) {
     $scope.categoryA = data;
     for (var i = 0; i < $scope.categoryA.length; i++) 
     $scope.arrayCategoryA[i] = true;
  });

});

1 Answer 1

2

$watchCollection takes a watch expression and in this case is the name of the scope variable of arrayCategoryA.

 $scope.$watchCollection(`arrayCategoryA`, function(newVal, oldVal){
    console.log("something changed");
  }, true);

Updated working plunkr

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

1 Comment

Thanks man, I have another little problem with a $watch function and multiple expressions. Please, see this updated code plnkr.co/edit/Wj3ICWeY17E2q0SlXk5z?p=preview

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.