user1260928
user1260928

Reputation: 3439

angularjs - $rootScope.$on called multiple times

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

Upvotes: 8

Views: 8637

Answers (1)

Ved
Ved

Reputation: 12113

$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

Upvotes: 19

Related Questions