加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:51:00 所属栏目:安全 来源:网络整理
导读:考虑我有100个控制器,我需要将一个滚动事件绑定到其中一个. 当控制器触发时,滚动事件监听器附加到文档并正常工作.但是当控制器改变时,滚动事件仍保持导致其他控制器出现问题! 我找到的唯一解决方案是解除所有其他99个控制器中的滚动事件的绑定,但这是愚蠢的
考虑我有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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读