Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save state of views in AngularJS

I develop a HTML 5 app, and have a view where user comments are loaded. It is recursive: any comment can have clickable sub-comments which are loading in the same view and use the same controller.

Everything is OK. But, when I want to go back, comments are loading again, and I lose my position and sub-comments I loaded.

Can I save the state of the view when I go back? I thought I can maybe use some kind of trick, like: append a new view any time I click on sub-comment and hide the previous view. But I don't know how to do it.

like image 634
Alex Avatar asked Mar 28 '14 13:03

Alex


People also ask

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

What is $state in AngularJS?

$stateProvider is used to define different states of one route. You can give the state a name, different controller, different view without having to use a direct href to a route. There are different methods that use the concept of $stateprovider in AngularJS.


1 Answers

Yes, instead of loading and keeping state of your UI inside your controllers, you should keep the state in a service. That means, if you are doing this:

app.config(function($routeProvider){
 $routeProvider.when('/', {
   controller: 'MainCtrl'
 }).when('/another', {
   controller: 'SideCtrl'
 });
});

app.controller('MainCtrl', function($scope){
  $scope.formData = {};   

  $scope./* other scope stuff that deal with with your current page*/

  $http.get(/* init some data */);
});

you should change your initialization code to your service, and the state there as well, this way you can keep state between multiple views:

app.factory('State', function(){
  $http.get(/* init once per app */);

  return {
    formData:{},
  };
});

app.config(function($routeProvider){
 $routeProvider.when('/', {
   controller: 'MainCtrl'
 }).when('/another', {
   controller: 'SideCtrl'
 });
});

app.controller('MainCtrl', function($scope, State){
  $scope.formData = State.formData;   

  $scope./* other scope stuff that deal with with your current page*/
});

app.controller('SideCtrl', function($scope, State){
  $scope.formData = State.formData; // same state from MainCtrl

});

app.directive('myDirective', function(State){
  return {
    controller: function(){
      State.formData; // same state!
    }
  };
});

when you go back and forth your views, their state will be preserved, because your service is a singleton, that was initialized when you first injected it in your controller.

There's also the new ui.router, that has a state machine, it's a low level version of $routeProvider and you can fine grain persist state using $stateProvider, but it's currently experimental (and will ship on angular 1.3)

like image 141
pocesar Avatar answered Oct 10 '22 04:10

pocesar