0

I am using angular router` to track the state of my web app like this:

when('/', { controller: "AController", templateUrl: "APanel.html" }). when('/subpage/:id', { controller: "BController", templateUrl: "BPanel.html" }). 

And I am using Angular Service to track some shared values:

app.service('stateService', function() { this.someSwitch = false; this.someLongDataArray = [x, y, z]; }); 

Currently, before changing path to \subpage\:id url from AController, I will assign new values to members of the service, so they can be referenced in subpages.

Now the question is, if user directly launching the subpage url \subpage\:id, or hit the refresh button on browser on subpage, BController will be invoked, and I will lost the values in the service which are supposed to be prepared by AController.

I am wondering what I should do in this case. is there any way I can get called when user launch the subpage directly, so I have a chance to prepare the data? (Maybe I can watch for html onload event, but not sure that's the best answer).

Thanks

2 Answers 2

1

It appears, BController is dependent on AController. Ideally, Controller should not contain any data/dom manipulaton, state maintenance. It is simply a glue between view and the $scope model. Being said so, you need not create any such dependency between controllers. The service can be invoked from both controllers.

OR If indeed there is a requirement that APanel.html must be loaded/initialized before BPanel.html is loaded, then you must check for some flag in BContoller and redirect user to APanel.html. like

if(<check some flag>){ $location.path('/'); } 

But then you have to find the way to redirect the user again to BPanel.html. I guess this is not a recommended approach.

Sign up to request clarification or add additional context in comments.

Comments

0

I am not sure I get your question completely. But if there is a possibility that the user might hit BPanel.html directly then you should do something like this.

if(serviceExists()){ //Do your usual Bcontroller stuff here if the services was initialized } else{ //Show a warning/error like "Oops, something is wrong go back to '/'" OR // Initialize services in BController } 

This should be in your BController if initializing your service before BController is that important. You basically force people to stay on AController.

2 Comments

Thank you, but I am not sure where this code should be placed? Should this code be placed in $scope.someFunction(){...} in BController? Or some other place that will be called when the controller is loaded?
the Bcontroller should be called whenever the route is loaded. So inside your BController code you should check before anything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.