How to prevent controller reloading when using ng-

2019-04-10 03:24发布

问题:

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.

回答1:

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.