我想知道为什么我的$手表没有被触发。这是相关控制器的代码段:
$scope.$watch('tasks',function (newValue,oldValue) { //do some stuff //only enters here once //newValue and oldValue are equal at that point }); $scope.tasks = tasksService.tasks(); $scope.addTask = function (taskCreationString) { tasksService.addTask(taskCreationString);//modifies tasks array };
在我看来,任务显然正在正确更新,因为我的长度限制像这样:
<span>There are {{tasks.length}} total tasks</span>
我缺少什么?
尝试$ watch(‘tasks.length’,…)或$ watch(‘tasks’,function(…){…},true)。
默认情况下,$watch不检查对象的等同性,只是为了参考。所以,$ watch(‘tasks’,…)将总是简单地返回相同的数组引用,这不会改变。
更新:Angular v1.1.4添加了一个$watchCollection()方法来处理这种情况:
Shallow watches the properties of an object and fires whenever any of the properties change (for arrays this implies watching the array items,for object maps this implies watching the properties). If a change is detected the
listener
callback is fired.