Question

According to this: How to deep watch an array in angularjs? it should work but i dont know what i am doing wrong...

    $scope.$watch('statuses', function(newVal, oldValue) {
      if (oldValue==newVal) return false;

      console.log("st changed");
    },true);

And let's say i somehow asynchronly update the $scope.statuses for example after 3seconds

setTimeout(function() {
    $scope.statuses.push("ahhh");
},3000);

And nothing happens...any ideas why please?

Was it helpful?

Solution 2

 $scope.statuses = [];

                $scope.$watch('statuses', function(newVal, oldValue) {
                  console.log(newVal, oldValue);
                  if (oldValue==newVal) return false;

                  console.log("st changed");
                },true);


                setTimeout(function() {
                    $scope.statuses.push("ahhh");
                    $scope.$apply();
                },3000);

$apply function serves for notification of update to $scope.

live sample http://plnkr.co/edit/LUjESyZOPfIALE2q5YYi?p=preview

if statuses will host just primitive values, better use $watchCollection

OTHER TIPS

Use the following code:

setTimeout(function() {
  $scope.$apply(function () {
    $scope.statuses.push("ahhh");
  }
},3000);

You have to use $apply since AngularJS is unaware of update to $scope

As a convenience, AngularJS provides $timeout, which is like setTimeout, but automatically wraps your code in $apply by default.

Use $timeout which is the Angular version of setTimeout. When you use $timeout, AngularJS rebinds everything after the callback.

Having to manually call $apply is always a sign that you did not do something the angular way. It's a way to tell Angular: I've done something behind your back; please refresh.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top