Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs - how to clean up controllers when navigating to a new route

I have a controller that loads a lot of data with an observable. If I navigate away from that route and the view is removed from the page how do I get informed of that in my controller so that I can stop the data load in the controller?

I basically want a deactivate function or clean up function that gets fired when the controller is no longer needed.

like image 802
Roaders Avatar asked Feb 11 '16 16:02

Roaders


1 Answers

You can listen for the $destroy event, and perform some clean-up/tear-down:

module.controller("SomeController", function($scope) {

    $scope.$on("$destroy", function() {
        // clean up here
    });
});

Resources:

  • $on: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$on
  • $destroy: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$destroy
  • http://odetocode.com/blogs/scott/archive/2013/07/16/angularjs-listening-for-destroy.aspx
  • See #12 from Top 18 most common AngularJS mistakes
like image 145
Luke Avatar answered Sep 25 '22 07:09

Luke