Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent re initialization of controller on $location.path()

I am working on an application where I have to insert a back navigation link to the main page from details page. Controllers for both views are different. I am using $location.path('/') to navigate back to the main page. Problem is, my controller for the main page is re-initialized when I navigate back by clicking on this link, which is not the expected behavior. Is there a way to prevent re-initialisation of the controller when routing back to the same link.

like image 256
Dania Avatar asked Sep 19 '13 16:09

Dania


1 Answers

I assume you're using AngularJS built-in routing module. If the controller in question is associated with a route, then it will be initialized whenever the route matches a new location. You cannot avoid it. If you don't want a controller to be created multiple times, you should define it high up in the view hierarchy. For example, the structure of main page could be something like this.

<html>
...
<body>
  <div ng-controller="SharedController">
    ...
    <ng-view></ng-view>
    ...
  </div>
</body>
</html>

Here, SharedController will be instantiated just once, regardless of which location users navigate to. You can move ng-view outside the div occupied by SharedController, although that will prevent scope inheritance from working, i.e. scopes inside ng-view will not prototypically inherit from the scope injected into SharedController.

Another option is using the third-party library ui-router which introduces the concept of nested states. With that, you could build a parent state with a controller that is instantiated just once as users access to different child states.

like image 135
Buu Nguyen Avatar answered Oct 07 '22 10:10

Buu Nguyen