2

I'm on page x. I click an action on page x which updates (with ajax) 3 div elements with new text.

Then I navigate to page y (with an angular request), and then back to page x - the values I changed with ajax are now gone (they are default).

My values are not inside a form, but rather inside a div element.

What is the simplest way to retain values between switching pages in angular in case some of them are changed (for example with ajax)?

Tool
  • 12,126
  • 15
  • 70
  • 120
  • Assuming you have a SPA when you're switching pages - then you can persist the data in a service or factory which will be cached as a singleton. – Michael Kang Jul 16 '14 at 22:08
  • Use an Angular service. Bind your DIV values to members exposed on your service. The service values will persist between pages. – Beyers Jul 16 '14 at 22:09

2 Answers2

3

You have a few options

  1. Save your data to $rootScope
  2. Create a service to store your data.
  3. Save your data to $cookieStore
Rob
  • 12,659
  • 4
  • 39
  • 56
3

Simplest? Set values on $rootScope.

$rootScope.name = name;

Now just inject $rootScope in any controller that needs name.

angular.module('myModule').controller('CtrlA', function($rootScope) { 
  $rootScope.name = "something";
});

angular.module('myModule').controller('CtrlB', function($rootScope) { 
  console.log($rootScope.name);
});

If you start to add a lot of values to rootScope you're probably better off using a service.

The service equivalent for something simple like a name is this:

angular.module('myModule').service('Name', function Name() {
  var name;

  var service = {       
   getName: function() { return name; },
   setName: function(n) { name = n; }
  };
  return service;
});

Then you can inject this service in different controllers.

angular.module('myModule').controller('CtrlC', function(Name) { 
  Name.setName('hello world!');
});

angular.module('myModule').controller('CtrlD', function(Name) { 
  $scope.name = Name.getName();
  console.log($scope.name);
});
Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83
  • How would I output the root variable in my view? – Tool Jul 16 '14 at 22:13
  • Just like any other scope variable - `{{name}}` – Andy Gaskell Jul 16 '14 at 22:13
  • is this applicable for Angular 1.5 component routing as well? I hv posted a que on stackoverflw http://stackoverflow.com/questions/39657136/how-to-retain-values-while-navigating-across-pages-using-component-routing-angul/ I apprecaite if u can u hav a look – ankitd Sep 23 '16 at 11:41