Angular.JS: views sharing same controller, model data resets when changing view

Controllers are disposed when changing routes. This is good behavior since you should not rely on controllers to carry data between views. It’s best to create a service to handle that data.

See the angular docs on how to use controllers correctly.
http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

To quote from the docs:

Using Controllers Correctly

In general, a controller shouldn’t try to do too much. It should contain only the business logic needed for a single view.

The most common way to keep controllers slim is by encapsulating work that doesn’t belong to controllers into services and then using these services in controllers via dependency injection. This is discussed in the Dependency Injection Services sections of this guide.

Do not use controllers for:

  • Any kind of DOM manipulation — Controllers should contain only business logic. DOM manipulation—the presentation logic of an application—is well known for being hard to test. Putting any presentation logic into controllers significantly affects testability of the business logic. Angular offers databinding for automatic DOM manipulation. If you have to perform your own manual DOM manipulation, encapsulate the presentation logic in directives.
  • Input formatting — Use angular form controls instead.
  • Output filtering — Use angular filters instead.
  • To run stateless or stateful code shared across controllers — Use angular services instead.
  • To instantiate or manage the life-cycle of other components (for example, to create service instances).

Leave a Comment