事件侦听器从同一指令多次触发

Event listeners fired multiple times from same directive

在我的应用程序中,我使用带有 window 调整大小事件侦听器的自定义指令:

link: function(scope, elem, attrs) {
    angular.element($window).bind('resize', function() {
        // viewId is a unique reference to the view in which the directive lives
        console.log(scope.viewId);
    });
}

该指令在我的每个视图中被插入 1 次或多次。

令我困惑的是为什么该功能不仅对活动视图执行,而且对非活动视图执行。一旦我访问了多个视图,就会发生这种情况。

更让我困惑的是,为什么在我多次访问同一个视图后,从同一个视图多次调用该函数。

在我看来,旧的指令作用域并没有被破坏,而是保持存在,并且在旧的作用域之上创建了一个新的作用域。

我能做些什么来防止这种行为吗?


下面是基于 Renan Lopes Ferreira 提供的答案的工作解决方案的代码片段(我使用 LoDash _.debounce 来防止函数被调用得太频繁):

windowResize = _.debounce(function () {
    // My logic
    $scope.$apply();
}, 150);

// Attach debounced function to the window.resize event listener
angular.element($window).on('resize', windowResize);

// Remove the function when the directive is destroyed
$scope.$on('$destroy', function () {
    angular.element($window).off('resize', windowResize);
});

当你的指令被销毁时,你需要移除监听器。类似于:

angular.element($window).on('resize', resize);

scope.$on('$destroy', function () {
  angular.element($window).off('resize', resize);
});

function resize(){
    ...
}

在指令 link 中,为找到每个具有相同名称 angular 的指令调用一次函数。

因此,如果您在视图中有两次指令,它将执行两次 link 函数。

如果您只想 运行 您的函数一次,只需在 "compile" 函数中执行您的操作即可。

看看这个教程,他很棒:http://www.sitepoint.com/practical-guide-angularjs-directives/