0

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.
1
  • what do you mean by fire controller initialize? A controller initializes every time it is encountered. You should probably read the controller documentation Commented Sep 12, 2014 at 12:14

3 Answers 3

2
  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)
      });
    });
    
Sign up to request clarification or add additional context in comments.

1 Comment

manual initialization is useful but I think angular should create an initial constructure like event.
1
  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()

Comments

0

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
});

Comments

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.