javascript - angularJS 为什么 $scope.$watch 不能工作?

标签 javascript angularjs angularjs-scope angularjs-watch

我想添加一个$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 henged,但什么也没有 请告诉我为什么,在 JSbin 中帮助我很好

最佳答案

使用$watchCollection作为数组对象

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

JSBin

关于javascript - angularJS 为什么 $scope.$watch 不能工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30476184/

相关文章:

javascript - 无法在 IE9 中从 Javascript 调用 BHO 方法

javascript - 如何从所有 JSON 值中删除引号并且不删除 Node JS 中 JSON 键中的引号

angularjs - 如何从 Instagram API 获取媒体?

javascript - 重置 Angular 页面

angularjs - 使用 'controller as' 语法将对象值传递给父 Controller

javascript - Angularjs - 范围的变化没有反射(reflect)出来

javascript - 有一个带有链接 Javascript 的 HTML 文档 我试图在单击提交按钮时添加一条警报消息。我该怎么做呢?

javascript - JQuery droppable out 事件有时不会用cursorAt 进行拖动

javascript - AngularJS:发布嵌套 JSON 参数

javascript - 从表单输入生成对象