我的目的是在范围内观察模型,并找出旧值和新值之间的差异.
但是,我发现以下代码中的旧值和新值都是相同的.
app.controller('MyCtrl', function($scope, $timeout){
$scope.markers = {};
$scope.$watchCollection('markers', function(newValue, oldValue){
console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
});
$timeout( function() {
$scope.markers.foo = 1;
}, 500);
$timeout( function() {
$scope.markers.bar = 2;
}, 500);
});
Run Code Online (Sandbox Code Playgroud)
输出:
being watched oldValue: Object {} newValue: Object {} script.js:6
being watched oldValue: Object {foo: 1} newValue: Object {foo: 1} script.js:6
being watched oldValue: Object {foo: 1, bar: 2} newValue: Object {foo: 1, bar: 2}
Run Code Online (Sandbox Code Playgroud)
为什么它们是相同的,如果它是故意的,为什么呢?
Dav*_*yon 36
$watch相反,你可以使用,这似乎工作.如果您想要观察对象上的所有属性(正如您所做的那样),则需要将true第三个参数添加到手表中.这设置了一个深刻的手表.
JS:
app = angular.module('myApp',[]);
app.controller('MyCtrl', function($scope, $timeout){
$scope.markers = {};
$scope.$watch('markers', function(newValue, oldValue){
console.log('being watched oldValue:', oldValue, 'newValue:', newValue);
}, true);
$timeout( function() {
$scope.markers.foo = 1;
}, 500);
$timeout( function() {
$scope.markers.bar = 2;
}, 500);
});
Run Code Online (Sandbox Code Playgroud)
rck*_*ckd 12
我发现检查新旧值是否相等(在值中)非常有用,如果是这种情况,则跳过该过程以避免意外行为.您可以使用angular.equals来实现这一点.这是一个例子:
JS:
$scope.$watch('myObject', function(newValue, oldValue){
if(angular.equals(newValue, oldValue)){
return; // simply skip that
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54269 次 |
| 最近记录: |