我正在使用 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/