4

In this example, using ng-switch, I'm able to switch between different views. Each view is assigned a controller.

I've put a quick sample online here : http://jsfiddle.net/FBHjZ/1/

It looks like the controller is reinstanciated everytime I switch views : If you enter a val in the input field, go to home and switch back to settings, the value is lost.

How can I prevent this? Basically, what I want is to keep state from previous views when I switch between views.

Florian F
  • 8,822
  • 4
  • 37
  • 50
  • 1
    If you're really interested in maintaining the state of them, why not just use ng-show and ng-hide to toggle their visibility? You could also use a custom directive to template/control your views, which would allow two way binding between the directive and it's host page, persisting the data. – Ben Lesh Oct 18 '12 at 17:17
  • Thx blesh, that's what I was looking for. Another question, is there an event I can listen to when an element is shown? (then calling a method on the controller) – Florian F Oct 18 '12 at 20:04

1 Answers1

6

There is no way of preventing the existing ngSwitch from re-instantiating controllers and re-creating a new scope. As noted in the documentation this directive is creating a new scope and actually creates / destroys corresponding DOM elements.

If you goal is to preserve state just put it in one of the parent scopes, check this jsFiddle: http://jsfiddle.net/FBHjZ/2/

An alternative approach is to use a service for the shared model.

pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • Hmm I see. So I'll use the ng-show/ng-hide solution from blesh for now because I want to avoir redrawing the screen each time. But your solution also works yep. – Florian F Oct 18 '12 at 20:06
  • 1
    Yeh, ng-show/ng-hide works well for small portions of the screen. With bigger DOM fragments it might be better to use ngSwitch (as it is adding / removing DOM elements, so the whole DOM tree is lighter). All depends on the use-case but since you've asked about the ngSwitch :-) – pkozlowski.opensource Oct 18 '12 at 20:22
  • Yup, but getting back to the previous state can become difficult to handle. Is there a way to keep the previous scope of an element and re-injecting it instead of creating a new one? My application is made of several tabs and subtabs and saving the state of each tab in a service seems difficult to manage – Florian F Oct 18 '12 at 20:53
  • In this case put your state in one of the parent scopes as in the jsFiddle attached to the response. This is like "preserving the state" – pkozlowski.opensource Oct 18 '12 at 21:04