AngularJS: binding a scroll event to one controller is not all

I have 100 controllers and I need binda scrollevent for one of them.

When the controller starts, the scroll event listener attaches to the document and works correctly. but when the controller changes, the scroll event remains and causes a problem in another controller!

The only solution I find is that the unbindevent is scrollin all the other 99 controllers, but this is stupid!

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

What is the right way?

+4
source share
3 answers

You can untie it when the scope of this controller is destroyed as follows:

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

.

2016 UPDATE

( ), . . Angular .

, $onInit(), $onDestroy:

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

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

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

.

+5

"$ destroy" "c1".

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

$route / .

angular.module('myApp')
.run(function ($rootScope, $document) {
    $rootScope.$on('$routeChangeStart', function(next, current) { 
       //Look for the appropriate controller here using next.controller object
       //and bind/unbind the events   
     });
});

$route https://code.angularjs.org/1.0.8/docs/api/ng. $route

, , - bind/unbind.

+2

All Articles