nj51
nj51

Reputation: 15

Angular view change resets $scope variables

Say I have two views that share a controller. Both views use the ng-route service. If a scope variable is changed in one view and then you switch to the second view, how come the second view doesn't update?

Example: My controller has a variable that = "hello". I output this variable just fine in both views. In view one I have an onclick that updates the variable to say "Whatsup". That works fine, but after the event I switch views and the second view is outputting "hello" still. Is there a way to share these? If not, then what is a technique to share data?

Upvotes: 1

Views: 547

Answers (2)

Jinw
Jinw

Reputation: 428

Best practice is to have one view per controller. As your site scales, it would get very hard to manage multiple templates/views with one controller.

A service is the way to share data between controllers.

For your example, you could have a activate functions that are called when each view is rendered that gets the updated variable from the service you inject. Your on lick function should save the variable to the service to make it available across controllers.

Upvotes: 0

jegtugado
jegtugado

Reputation: 5141

I'd like you to know that AngularJS is designed for SINGLE PAGE APPLICATIONS (SPA) so this behavior is not supported by the framework.

Each view have a different scope even though they share the same controller. So updating a scope variable for one view won't update the other.

If you want this behavior, I suggest using $on to listen to events.

Also, on your code you have $scope.test = 'hi'; that is hard-coded on your controller with no conditions or whatsoever which is why it reflects on both of your views who share the same controller.

Upvotes: 0

Related Questions