0

I want to add a $watch to watch $scope.data is changed or not, but it cant't work

[http://jsbin.com/biqesojaqu/1/edit?html,js,console,output][1]

app.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-app="App" ng-controller="TestController">
<div>
  <ul>
    <li ng-repeat="item in data"> {{ item.name }}--{{ item.status }}</li>
    <button ng-click="addOnePerson()">ADD</button>
  </ul>
</div>
</body>
</html>

app.js

var App = angular.module("App", []);

App.controller('TestController', function ($scope) {
  $scope.data = [
    {name: 'cc', status: true},
    {name: 'bob', status: false}
  ];
  $scope.name = 'nataila';
  $scope.addOnePerson = function () {
    var personCount = $scope.data.length;
    personCount += 1;
    $scope.data.unshift({name: 'cc'+personCount, status: true});
  };
  $scope.$watch('data', function (){
    console.log('has changed');
  });
});

when I click the button, I think console will output has chenged, but it's nothing please tell me Why, and it's Good to help me in JSbin

nataila
  • 1,549
  • 4
  • 18
  • 25
  • `$scope.$watch` watches if the variable gets a new value assigned. As @Zee states, use `$watchCollection` to see if an array has new values or removed ones – devqon May 27 '15 at 07:51
  • try to use $scope.$watch('data',function(){},true); It help you alot It worked for me – Shubham Nigam May 27 '15 at 07:52
  • possible duplicate of [$watch an object in angular](http://stackoverflow.com/questions/19455501/watch-an-object-in-angular) – dting May 27 '15 at 07:55

1 Answers1

2

Use $watchCollection for an array or object

$scope.$watchCollection('data', function (){
  console.log('has changed');
});

JSBin

Zee
  • 8,420
  • 5
  • 36
  • 58