How to preserve field values when switching tabs?


#1

How would you go about preserving fields values within a tab content when switching to another tab and going back?

See http://codepen.io/esartor/pen/Erhpw and notice that if you type something in the text field of tab 1, then switch to tab 2 and go back to tab 1, the field value is reset.


#2

There are two issues you’re facing -

  1. Ionic will work differently in the browser and on a smartphone/simulator. This is because AngularJS may or may not do what you ask it to in a browser.

  2. You’re not saving anything! When you enter some text in Tab1, that data needs to be saved somewhere to be recovered. This is because the entire tab gets redrawn when you come back. The solution to this is the scope variable. You need to read a bit about it here.

Finally, read the excellent App Guide in the Ionic Docs. It tells you how scope works with ionic.

Lastly, the key thing to understanding all this will be for you to write a function that saves the text in a $scope.variable as the user types it. Then, when the user switches tabs and comes back, you check if the scope has any value and put that value back into the textarea. Simple.


#3

Actually, saving the text in a $scope var isn’t enough as the Tab1 scope is lost when I switch to Tab2. I updated the code to reflect that behaviour: http://codepen.io/esartor/pen/Erhpw?editors=101

I think I’d have to persist those values in a less volatile place, like sessionStorage for example.


Preserve View State While Navigating
#4

see Pen here http://codepen.io/aaronksaunders/pen/jeFmC


#5

@aaronksaunders, thanks! That’s exactly what I needed!


#6

Thanks @aaronksaunders for the solution.

example of three tabs (same for any number of tabs)

For others the solution is as follows.

  1. Move the controller into the directive
    <ion-tabs>.

  2. Add an alias to the controller. For example if
    ion-tabs

looks like

<ion-tabs ng-controller="myController">

Change this to the following

<ion-tabs ng-controller="myController as main">:
3. The controller alias is now the word “main”. Now add the alias word to all your tab ng-model’s . For example if an input is

<input type="text" ng-model="textValue" placeholder="Tab1 old wrong setup input text here" />

Change it to the following

<input type="text" ng-model="main.textValue" placeholder="Tab1 correct setup input text here" />

#7

Hi,

And What if we declare the controller in the Route ?
Like this ?

  .state('Start', {
    url: '/start',
    controller: 'startCtrl'
  })