简体   繁体   English

angularJS为什么$ scope。$ watch无法工作?

[英]angularJS why $scope.$watch cant't work?

I want to add a $watch to watch $scope.data is changed or not, but it cant't work 我想添加一个$ watch来监视$ scope.data是否已更改,但无法正常工作

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

app.html 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 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 当我单击按钮时,我认为控制台将输出has chenged ,但请告诉我原因,这没什么,用JSbin帮助我很好

Use $watchCollection for an array or object arrayobject使用$watchCollection

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

JSBin 联合会

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM