Angular Watch和ng-click事件序列

Dou*_*eux 10 angularjs

我在angular指令中有这个代码,我发现$ watch行为有点令人困惑.updateSelect在"ng-click"中调用:

scope.updateSelect = function (type) {
    scope.selectionCtrl.activeList = scope.seedLists[type]; 
    scope.selectionCtrl.activeListKey = type; 
    scope.selectionCtrl.activeSelection = scope.selection[type];
    scope.selectionCtrl.staged = [];
    scope.selectionCtrl.stageRemove = [];
    if (type !== scope.activeTab) {
        scope.activeTab = type;
    }
    console.log("update");
};

scope.$watch('selectionCtrl.activeList', function(newValue, oldValue) {
    console.log("watch");
}, true);
Run Code Online (Sandbox Code Playgroud)

当我点击按钮(触发updateSelect),并观察控制台时,我看到"更新"然后"观看".函数内部发生的第一件事selectionCtrl.activeList是设置,所以我希望看到"监视"然后"更新".

一旦阵列发生变化,不应该立即观察触发器吗?

Gru*_*nny 2

由于 javascript 是单线程的,该函数必须首先完成。

因为该函数是通过 ng-click 指令调用的,所以 Angular 将运行一个摘要循环。该摘要周期的一部分是运行监视列表并解决自上次运行周期以来可能发生的所有更改。

在您给出的示例中,selectionCtrl.activeList 在 updateSelect 中发生更改,随后导致调用监视回调。