$watch 没有被解雇

$watch not being fired

我正在使用来自 AngularJS implementation of ScrollSpy (original article here) 的代码,但是当我的导航是动态创建时 运行 遇到了问题,但是当导航是静态创建时它确实有效。

所以我有一个 scrollSpy 指令监视 spies 的列表。 spies 列表基本上是一个导航元素列表,它应该在用户滚动页面时突出显示。 spies 是通过 scrollSpy 控制器中的 addSpy 方法添加的,就像这样

controller: function ($scope) {
    $scope.spies = [];
    return this.addSpy = function (spyObj) {
        return $scope.spies.push(spyObj);
    };
},

addSpy 函数总是被调用,但是当我动态添加间谍时,该列表的 $watch 永远不会被触发,它会在静态创建导航项时被触发。

link: function (scope, elem, attrs) {
    scope.$watch('spies', function (spies) {
        // I never get called when spies are added dynamically, even 
        // though spies are added to the $scope.spies object in the controller!
    }

谁能帮我理解为什么 $watch 没有被解雇?我尝试向其中添加 $scope.$apply,但它说它已经在摘要循环中。

scope.$watch('spies', function (spies) {
    // I never get called when spies are added dynamically, even 
    // though spies are added to the $scope.spies object in the controller!
}, true);

你必须在最后添加 ,true,因为你没有更改引用,只是更新它。