Dania
Dania

Reputation: 1017

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.

Upvotes: 8

Views: 2837

Answers (2)

Dania
Dania

Reputation: 1017

As I had more than one apps in my angular project, It was difficult to implement answer posted above as I have my ng-view much above in hierarchy that decides which app to be displayed to user. So, the solution is to store data inside a service. Service do not re instantiate when navigate within an app, so the data remains intact.

Inside controller,

// Check if data is present in service

if (service.dataModel && service.dataModel.data) {
    // insert data in scope variables here
} 

else {
   // fetch data from server and add data model to service.
}

Upvotes: 0

Buu
Buu

Reputation: 50335

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.

Upvotes: 5

Related Questions