0
votes

I have a problem with angularjs. 2 have 2 views :

  1. View 1 has these controls
    • A textbox named txtBox1 with a default blank value
    • A button named "Change" to change text in txtBox1 to "Changed !"
  2. View 2
    • A textbox named txtBox2

First I navigate to View1, click the button, txtBox1's content is changed to "Changed !". Then I navigate to View2, after that, I back to View1.

So how could I keep the data I typed into txtBox1 from View1 ? I have used DurandalJs, they have view caching option to keep current data on view when navigating, but I don't know how to do with angularjs?

enter image description here

1
Some simplified code could help, but the basic idea is that you should create a dataservice that is used by both controllers and that stores the value on view 1. That will also allow view2 to access it if needed. If that's not needed, view2 does not need to reference the service, because it will be instantiated by the app and remain instantiated until the app closes.Beartums
can you post your code.?Ved

1 Answers

0
votes

@jimmy ng: Do you want your data to be stored even after refresh? It's important.

If you just want those values there for current app run and presuming that you have 1 ctrl for each main view, then you can store your form data via helper service class (data manager service):

myapp.service('viewDataManager', [function () {
  var data = {};
  // TODO: optionally via HTML5 getter/setter way
  return {
    get: function (key) { return data[key]; },
    set: function (key, newData) { data[key] = newData; }
  };
}]);

Then, in the destroy of view1Controller you just set your form data:

 $scope.$on('$destroy', function () {
   view1DataManager.set('view1FormData', $scope.myModel.formStates);
 });

Again, on init/constructor, reload those states:

 $scope.init = function () {
   $scope.myModel.formStates = view1DataManager.get('view1FormData');
 };

This is for having the data kept for current run of the app. For future instances, just update the data manager to set this to localStorage or websql or even cookie (not too recommended though).

NOTE: You can store just about everything in $rootScope as well, but that is just hardcore from any way you would look at it (architecture, performance, etc). So definitely a "don't go there" thing.

UPDATE: @jimmyng : It's basically impossible to store those states in the object (aka ctrl) because the object is being (of course) trashed and instantiated again on demand.

Presuming all your UI volatile data is stored in "formStates", the above code will handle what you need. You are working with AngularJS so widgets will be bound to ng-model. You can also put there the options for the selects and so forth.

// E.g.:
dropdownlist ---> ng-model -> formStates.selectedXXX
dropdownlist ---> ng-options-> formStates.xxxOptions
textbox ---> ng-model -> formStates.name
etc