angularJS 为什么 $scope.$watch 不能工作?
angularJS why $scope.$watch cant't work?
我想加个$watch看$scope.data有没有变化,但是不行
[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');
});
});
当我点击按钮时,我认为控制台会输出 has chenged
,但它什么都没有
请告诉我为什么,在 JSbin
中帮助我很好
对 array
或 object
使用 $watchCollection
$scope.$watchCollection('data', function (){
console.log('has changed');
});
我想加个$watch看$scope.data有没有变化,但是不行
[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');
});
});
当我点击按钮时,我认为控制台会输出 has chenged
,但它什么都没有
请告诉我为什么,在 JSbin
对 array
或 object
$watchCollection
$scope.$watchCollection('data', function (){
console.log('has changed');
});