2

I have a controller like this:

myApp.controller('loginCtrl', ['$scope', '$rootScope', '$http', '$location', function($scope, $rootScope, $http, $location){

    console.log('check 1');

    // before route update
    //---------------------------------------------------------
    $rootScope.$on('$locationChangeStart', function(event){
        if($location.path() == "/login"){
            console.log('check 2');
        }
    });

}]);

First time check 1 will be logged and When i click on /login link, check 2 will be logged. everytime i change path to /home and /login, i expect a new check 2 on console but what i see in console is like this:

check 2 (1 time)
check 2 (2 times)
check 2 (3 times)
check 2 (4 times)
...

this means by every location change, angularjs creates a new listener and number of check 2's increases! Is there a standard way for listening on location change without this issue? or should i remove my listener before leaving /login page?


OTHER FILES

my app.js file:

...
when('/login', {
  templateUrl: 'page/login.html', 
  controller: 'loginCtrl', 
  reloadOnSearch: false
})
...

login template:

<section class="login-page section">
    <h3>Login</h3>
    ...
</section>

1 Answer 1

1

This is because you are subscribing with $rootScope.$on in your controller. When you subscribe this way, AngularJS has no chance to clean up the listeners for you when your local $scope is destroyed.

Just subscribe with $scope.$on('$locationChangeStart', fn); If you subscribe this way AngularJS will automatically remove the listener when your local $scope is destroyed.

Sign up to request clarification or add additional context in comments.

1 Comment

What about if you are subscribing to an event not generated by AngularJS? E.g. Parsley generates events to which one subscribes using $.listen. This will register a listener each time one hits the controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.