0

Say I have a few dynamic div elements setup by ng-repeat. When I click this element it toggles a class on the div like how a radio button would be by letting you only select one div at a time.

Is it possible through something like local storage to retain that selected state using AngularJS so when I visit the page later it knows which element to select?

Ronnie
  • 11,138
  • 21
  • 78
  • 140
  • Instead of saving the elements themselves save your JS object acting as the data layer (the $scope of the controller in a lot of cases) (possibly in the local storage), then restore it from there and data binding should take care of the rest for you. – Benjamin Gruenbaum Aug 27 '13 at 20:40
  • @BenjaminGruenbaum That is the plan. The way I reference the element right now when I navigate back (not actually changing pages yet) is actually save a reference to the element in my object. I am just not sure if when I reload the page and come back that reference will actually be accurate – Ronnie Aug 27 '13 at 20:42

1 Answers1

1

Depends. Do you want the state to be saved even if the user leaves the site or reloads the page, or just while clicking around in Angular?

If you only want the second, which is honestly enough if you are just looking to speed up the site a bit, you can save the state in a service. Services only have one instance so if you save something in a service and access it later it will contain the same data. However, this is still just saved inside the javascript, so an actuall page refresh or leaving the site will drop it. See the answer here for more info.

If you want to persist for longer than that you need to use cookies or local storage. Angular has an extra plugin that you can download called angular-cookies that gives you the $cookies service to handle cookies. $cookies has some problems however, it does not allow you to set the path for the cookie, which makes it a no-go in several scenarios, and it does not handle local storage. So it might work for you, but you might need to create your own system for it or find someone else who has.

Community
  • 1
  • 1
Erik Honn
  • 7,576
  • 5
  • 33
  • 42
  • I definitely need the state saved when the user leaves the site or reloads the page. I'll look into this cookies thing. My overall goal is a user goes through 5 steps, saves their state. Comes back at a later time and can load up their previous steps – Ronnie Aug 27 '13 at 21:26
  • Yeah, $cookieStore is really easy to use. – Zack Argyle Aug 27 '13 at 22:22
  • Then cookies (or local storage for newer browsers) is the thing for you. – Erik Honn Aug 28 '13 at 11:27