【问题标题】:$watch not being fired$watch 没有被解雇
【发布时间】:2015-10-07 05:17:38
【问题描述】:

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

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

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,但它说它已经在摘要循环中。

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-watch


    【解决方案1】:
    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,因为您没有更改参考,只是更新它。

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2016-07-15
      • 2021-04-05
      相关资源
      最近更新 更多