How to prevent controller reloading when using ng-switch

Florian F picture Florian F · Oct 18, 2012 · Viewed 7.1k times · Source

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.

Answer

pkozlowski.opensource picture pkozlowski.opensource · Oct 18, 2012

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.