【问题标题】:angularJS why $scope.$watch cant't work?angularJS 为什么 $scope.$watch 不能工作?
【发布时间】:2015-08-09 04:02:26
【问题描述】:

我想加一个$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中帮助我很好

【问题讨论】:

  • $scope.$watch 监视变量是否获得了分配的新值。正如@Zee 所说,使用$watchCollection 查看数组是否有新值或已删除的值
  • 尝试使用 $scope.$watch('data',function(){},true);它对你有很大帮助它对我有用

标签: javascript angularjs angularjs-scope angularjs-watch


【解决方案1】:

$watchCollection 用于arrayobject

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

JSBin

【讨论】:

  • 请看这段代码link
  • @nataila。那个链接是干什么用的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
相关资源
最近更新 更多