angularJS为什么是$scope ?我的手表坏了

angularJS why $scope.$watch cant't work?

本文关键字:我的 手表 坏了 scope 为什么 angularJS      更新时间:2023-09-26

我想添加一个$watch到watch $scope。数据被更改或未更改,但它不能工作

[http://jsbin.com/biqesojaqu/1/edit?html, js、控制台、输出][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

$watchCollection代替arrayobject

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

JSBin