我有以下代码片段
function MyCtrl($scope, $log){
$scope.name = 'guy';
$scope.guy = {};
function myWatch(){
return function(newValue, oldValue){
$log.info('these are the values',newValue, oldValue);
if ( newValue === oldValue ){
$log.info('they are the same');
}
}
}
$scope.$watch('guy',myWatch(), true);
$scope.guy = { 'hello' : 'world' };
}
你可以run on plunkr - 寻找控制台打印!
想法是:
- 为范围属性赋值
guy
- 设置
$watch
在那个属性(property)上 - 将另一个值赋给
guy
- 期待
newValue
和oldValue
与众不同,看不见they are the same
在控制台日志中打印 - 失败- 更具体地说,我希望
oldValue
成为{}
newValue 为{ 'hello':'world' }
- 更具体地说,我希望
我做错了什么,需要时我应该如何实现这个逻辑?
最佳答案
watch 没有额外的变化,因为 watch 是作为摘要周期的一部分进行评估的。我创建了一个更改函数中的 guy
的示例,通过单击按钮调用。
我还调整了您的 watch 函数,使其成为函数而不是返回函数的函数。
function myWatch(newValue, oldValue){
$log.info('these are the values',newValue, oldValue);
if ( newValue === oldValue ){
$log.info('they are the same');
}
}
$scope.$watch('guy',myWatch, true);
关于javascript - Angular `watch` 未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300411/