angularjs $看老值和新的价值是相同的 [英] angularjs $watch old value and new value are the same
问题描述
我的目的是看范围内的模型,发现旧值和新值之间的差异。
My intention is to watch a model within scope, and find difference between old value and new value.
不过,我发现旧价值和新价值从以下code都是一样的。
However, I found old value and new value are all the same from the following code.
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);
});
输出:
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}
为什么他们一样的,如果是故意的,那么为什么?
Why are they the same, and if it's intentional, then why?
这里是code,<一个href=\"http://plnkr.co/edit/rfMCF4x6CmVVT957DPSS?p=$p$pview\">http://plnkr.co/edit/rfMCF4x6CmVVT957DPSS?p=$p$pview
推荐答案
您可以使用 $观看
来代替,这似乎工作。如果你想要观看的对象上的所有属性,以及(如你正在做的),你需要添加真正
作为第三个参数的手表。这就建立了深刻的手表。
You can use $watch
instead, that seems to work. If you want to watch all the properties on the object as well (as you are doing), you need to add true
as the third parameter to the watch. This sets up a deep watch.
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);
});
这篇关于angularjs $看老值和新的价值是相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!