我一直在使用$ watchGroup来观察一系列的字段并触发一系列的功能,具体取决于某个特定字段是否已被更改。
我设置了以下plnkr来演示我遇到的意外行为。
$scope.$watchGroup(['first', 'second', 'third'], function(newValues, oldValues)
{
var message =
{
first: newValues[0],
second: newValues[1],
third: newValues[2],
firstOld: oldValues[0],
secondOld: oldValues[1],
thirdOld: oldValues[2]
};
if(newValues[0] !== oldValues[0]){
console.log('First changed')
}
if(newValues[1] !== oldValues[1]){
console.log('Second changed')
}
if(newValues[2] !== oldValues[2]){
console.log('Third changed')
}
$scope.messages.push(message);
});
该场景涉及三个观看的领域,我想触发一个功能取决于哪个领域已经改变。我一直在使用'newValues'和'oldValues'来监视哪个字段发生了变化。
我碰上了,问题是,如果我已经改变了“二”字段,然后去改“第一”或“第三”字段,将触发“第二”功能作为其存储先前“ newValues'和'oldValues',这使得它看起来像“Second”字段已经改变,如此image中所示。
我突出了图片中的异常。我希望一旦我开始改变“第三”领域,“第二”的'newValues'和'oldValues'就像它不是场改变一样。
我知道我可以坚持两个级别的旧值,并比较它们来解决这个问题,但我希望它能像我所描述的那样工作。任何澄清,如果这是一个错误或预期的功能,将不胜感激。
$ watchGroup的angular文档声明watchExpressions是一个“将使用$ watch()”单独观看的表达式数组。这使我认为这不是预期的功能。
我在与一些类似的问题,我正在确认并且希望能够分辨哪个watchExpression触发了$ watchGroup侦听器函数。想听听这个解决方案! –