1

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?

yugantar kumar
  • 1,982
  • 1
  • 23
  • 33
nj51
  • 15
  • 2

2 Answers2

0

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.

jegtugado
  • 5,081
  • 1
  • 12
  • 35
  • Oh, ok. I was confused because a lot of these apps have different views which make it feel like its more than one page. My project was going to be an app to help employees pick up different shifts. The two main pages were 1. A place to show available shifts to choose from 2. A page that shows the shifts a user has picked Is this something angular would be bad for? – nj51 Jul 21 '16 at 00:15
  • No, angular will work for you. You might be confused on what SPA is, see the definition [here](http://stackoverflow.com/a/19501759/6138713). Long story short, if you want to update another view (page) or controller, use `$broadcast` and `$on`. – jegtugado Jul 21 '16 at 00:22
0

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.

Jinw
  • 428
  • 5
  • 10