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


i'm getting started angular.js.

i have number of views share same controller. each view step in collecting data stored in controller:

$routeprovider.when('/', {   templateurl: 'partials/text.html',   controller: 'itemsubmitter' });  $routeprovider.when('/nextthing', {   templateurl: 'partials/nextthing.html',   controller: 'itemsubmitter' }); 

the itemsubmitter controller:

$scope.newitem = {   text: null } 

here's first view:

<textarea ng-model="newitem.text" placeholder="enter text"></textarea>  <p>your text is: {{ newitem.text }}</p> 

this works, live updating 'your text is:' paragraph.

however when next view loaded, {{ newitem.text }} reset default value. how can make values stored in controller instance persist across views?

controllers disposed when changing routes. behavior since should not rely on controllers carry data between views. it's best create service handle data.

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

to quote docs:

using controllers correctly

in general, controller shouldn't try much. should contain business logic needed single view.

the common way keep controllers slim encapsulating work doesn't belong controllers services , using these services in controllers via dependency injection. discussed in dependency injection services sections of guide.

do not use controllers for:

  • any kind of dom manipulation — controllers should contain business logic. dom manipulation—the presentation logic of application—is known being hard test. putting presentation logic controllers affects testability of business logic. angular offers databinding automatic dom manipulation. if have perform own manual dom manipulation, encapsulate 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 life-cycle of other components (for example, create service instances).

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -