javascript - Angujar 1.3 无法使用 $watch 更改数据

标签 javascript angularjs watch

我正在使用 Angular.js 制作一个网页,其中我在表格中显示数据并且用户可以编辑。每当数据发生变化时,我需要运行一个javascript函数,所以我的想法是使用$scope$ watch。我的问题是,数据发生变化,但 $scope$ watch 不运行。

这是我的代码(app.js)的一小部分

app.controller('DataCtrl', function($scope, ngTableParams) {
  $scope.datos = [{x:1, y:2},
                {x:3, y:5},
                {x:2, y:8}];

  $scope.tableParams = new ngTableParams({
    page: 1,    // show first page
    count: 20,   // count per page
    }, {
      total: $scope.datos.length, // length of data
      getData: function($defer, params) {
              $defer.resolve($scope.datos);
      }
  });
  // add new line
  this.addLine = function() {
    $scope.datos.push({
      x: null,
      y: null,
    });
  };
  //delete data
  this.deleteLine = function(index){
    $scope.datos.splice(index, 1);
  };

  $scope.updated = -1;
  $scope.$watch('datos', function(){
        $scope.updated++;
    });

});

我做错了什么?这是最好从看到的是数据变化? 坦克。

最佳答案

使用对象相等标志,这样它就不会使用引用相等:

  $scope.$watch('datos', function(){
      $scope.updated++;
  }, true);

或者,按照 Deuterium 的建议使用 $watchCollection:

  $scope.$watchCollection('datos', function(){
      $scope.updated++;
  });

关于javascript - Angujar 1.3 无法使用 $watch 更改数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938302/

相关文章:

bash - 更新 bash 中 watch 命令中的变量

angularjs - Angular : watch not working inside loop

javascript - 使用 javascript 获取 DIV 的内容,.innerHTML 不起作用?

javascript - 页面加载后淡入元素

javascript - 获取数组内部的数组

javascript - 在嵌套的 json 数据 Angular js 的情况下,如何为 ng-options 设置默认值?

javascript - 在 AngularJS 中深入 $watch 一个集合

javascript - JS DOM 对象和样式属性

javascript - 为什么这个简单的 javascript 代码不起作用?

javascript - native 日期选择器 - 有没有办法通过 javascript 触发它