Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs - $rootScope.$on called multiple times

Tags:

angularjs

In one controller I do :

$rootScope.$emit("newAction", {});

in another controller I do :

$rootScope.$on('newAction', function() {
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
      });

My problem is that $rootScope.$on is called multiple times. I don't know why.

If anybody has a hint... Thanks

like image 870
user1260928 Avatar asked Jun 20 '16 10:06

user1260928


1 Answers

$rootScope listener are not destroyed automatically. You need to destroy it using $destroy.

var customeEventListener = $rootScope.$on('newAction', function() {
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
          vm.newAction (...);
      });

$scope.$on('$destroy', function() {
        customeEventListener();
  });

Refer this link
Working with $scope.$emit and $scope.$on

like image 183
Ved Avatar answered Oct 10 '22 14:10

Ved