AngularJS:将滚动事件绑定到一个控制器而不是全部

علی*_*رضا 5 scroll javascript-events angularjs

考虑我有100个控制器,我需要bind一个scroll事件给其中一个.

当控制器触发时,滚动事件监听器附加到文档并正常工作.但是当控制器改变时,滚动事件仍然存在并导致其他控制器出现问题!

我发现的唯一解决方案是所有其他99个控制器中unbindscroll事件,但它是愚蠢的!

angular.module('test', ['ngRoute'])
.config(function($routeProvider){
    $routeProvider
        .when('/c1', {controller:'c1', templateUrl:'/c1.html'})
        .when('/c2', {controller:'c2', templateUrl:'/c2.html'})
        ...
        .when('/c100', {controller:'c100', templateUrl:'/c100.html'})
        .otherwise({redirectTo: '/c1'});
})
.controller('c1', function($document){
    ...
    $document.bind('scroll', function(){...});
    ...
})
.controller('c2', function($document){
    $document.unbind('scroll');
    ...
})
...
.controller('c100', function($document){
    $document.unbind('scroll');
    ...
})
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法?

Nob*_*ita 5

当控制器的范围被破坏时,您可以取消绑定它,如下所示:

.controller('c1', function($document, $scope){
  $document.bind('scroll', function(){...});
  // .....
  $scope.$on('$destroy', function() {
    $document.unbind('scroll'); 
  });
})
Run Code Online (Sandbox Code Playgroud)

有些人在这里阅读.

2016年更新

如果您现在正在使用组件(并且您应该),则可以轻松且更好地更新此方法.只需利用新语法并掌握Angular为这些情况提供的生命周期钩子.

所以,绑定你的$onInit(),解开你的$onDestroy:

class SomeComponentName {
   constructor($document) {
      this.$document = $document;
   }

   $onInit() {
      this.$document.bind('scroll', evt => {});
   }

   $onDestroy() {
      this.$document.unbind('scroll');
   }
}
Run Code Online (Sandbox Code Playgroud)

更多关于生命周期钩子的信息.