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

前端之家收集整理的这篇文章主要介绍了AngularJS:将滚动事件绑定到一个控制器并不是全部前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑我有100个控制器,我需要将一个滚动事件绑定到其中一个.

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

我找到的唯一解决方案是解除所有其他99个控制器中的滚动事件的绑定,但这是愚蠢的!

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');
    ...
})

什么是正确的方法

解决方法

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

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

一些关于它的阅读here.

2016年更新

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

所以,绑定你的$onInit(),取消绑定你的$onDestroy:

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

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

   $onDestroy() {
      this.$document.unbind('scroll');
   }
}

更多关于生命周期钩here.

猜你在找的Angularjs相关文章