Prevent controller reinitialization at $ location.path ()

I am working on an application where I need to insert a navigation back link to the main page from the detailed page. The controllers for both types are different. I use $location.path('/') to go to the main page. The problem is that my controller for the main page is reinitialized when I go back by clicking on this link, which is not the expected behavior. Is there a way to prevent the controller from reinitializing when routing back to the same link.

+8
angularjs angularjs-routing
source share
2 answers

Since I had several applications in my angular project, it was difficult to implement the answer posted above, since I have my ng-view much higher in the hierarchy, which decides which application will be displayed to the user. So the solution is to store data inside the service. The service is not created when navigating in the application, so the data remains intact.

Internal 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. } 
0
source share

I assume that you are using AngularJS built-in routing module. If the corresponding controller is associated with a route, it will be initialized whenever the route matches a new location. You cannot avoid this. If you do not want the controller to be created several times, you must define it high in the hierarchy of views. For example, the structure of the main page may be something like this.

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

Here, the SharedController will be created only once, no matter what location users will be moved to. You can move the ng-view beyond the div occupied by the SharedController , although this will prevent sphere inheritance from working, i.e. The areas inside the ng-view will not prototypically inherit from the area entered in the SharedController .

Another option is to use a third-party ui-router library that introduces the concept of nested states. In doing so, you can create a parent state with a controller that is created only once when users get access to various child states.

+5
source share

All Articles