barteloma
barteloma

Reputation: 6855

angularjs destroy and initialization events

I am firing the destroy functions to handle destroy of controller.

    $scope.$on("$destroy", function() {
       alert(0)
    });

I have links that calls controller with stateProvider.

<a href ="#/product">products</a>
<a href ="#/categories">categories</a>

when I click products link while working on category page, destroy handler function is firing.

  1. who is destroyed the controller scope when click another link? stateProvider or else?
  2. how can I fire controller initialize function like destroy.

Upvotes: 0

Views: 2156

Answers (3)

noypi
noypi

Reputation: 991

  1. a new controller gets created every route, so the old controller needs to go. and the new one comes in.

  2. element.scope().$destroy()

Upvotes: 1

bmleite
bmleite

Reputation: 26880

  1. The controller is destroyed internally by Angular. By "who" exactly is not really important.

  2. If you want to run a certain function when the controller is created, then just call it directly in the controller's "body":

    .controller('Ctrl', function($scope) {
      var initialize = function() {
        // do some stuff when the controller is created 
      };
    
      initialize();
    
      $scope.$on("$destroy", function() {
        alert(0)
      });
    });
    

Upvotes: 2

Cathal
Cathal

Reputation: 1790

when you click the product link you're moving away from the category view and it's controller. Since the controller is no longer in scope it is destroyed. I think something like routeChangeStart or routeChange success would suit you better. One is fired when the you click the link, the other is fired when you successfully navigate depending on where you want to execute the code. If you're in the category page moving to the product page the routeChangeStart code would be executed by the category ctrl and routeChangeSuccess by the product. eg in product controller:

$scope.$on( "$routeChangeStart", function(event, next, current) {
  //execute something here
});

Upvotes: 0

Related Questions