Pavel Shorokhov
Pavel Shorokhov

Reputation: 4994

Angular UI Router: How to save parent state?

I use IonicFramework, Angular UI Router and Nested Views.

Example of my routing:

// Method app.config()
$stateProvider
      .state('main', {
        url: '',
        views: {
          '@' : {
            templateUrl: 'layout/main.html'
          },
          'topbar@main' : {
            templateUrl: 'component/topbar/topbar.html'
          },
          'content@main' : {
            templateUrl: 'component/pager/pager.html'
          }
        }
      })
      .state('settings', {
        templateUrl: 'component/settings/settings.html'
      })
    ;

I try to go from 'main' to 'settings' state - all ok: $state.go('settings').

When I try to click '< Back' and return, main state reset to initial state.

I found a hint here that the 'settings' must be a child of the 'main'. But I do not know how to implement it. All my attempts failed.

Question: How to switch to another view, saving state of the previous view?

Thanks.

Upvotes: 0

Views: 1643

Answers (1)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10163

ui-router does nothing regarding saving the application state. The solution here is to use a service where you persist your application state/data (in AngularJS's implementation a service is a singleton).

So basically this:

angular.service('MyService', function() {
    var data = {};

    return {
        get: function() {
            return data;
        }
    };
});

function State1Controller($scope, MyService) { // you rely on AngularJS's built-in $injector

    $scope.data = MyService.get();
}

Now every time you use this controller, $scope.data will point to the same object reference inside the service (it's a singleton). So any changes you make to $scope.data will be "saved" regardless of the controller you are using it in or how many state changes you perform.

Also, keep in mind that doing a $scope.data = {}; will break this "trick" if you are using it in multiple controllers loaded in the same state as it assigns a new reference to $scope.data. You should never overwrite it unless you know what you are doing.

Upvotes: 0

Related Questions