kapoorji kapoorji - 1 month ago 11
AngularJS Question

Angular JS App persist state on browser refresh

I have angular Js App with nested views, the issue i am facing is when i click on F5 in nested view it gets redirected to default state, i want to persist the current state.

I can understand on reload it goes to parent ui-view to load the dependencies and after that it redirects to default view i have mapped but how can i redirect it to initial view instead of default view.

routes.js

$urlRouterProvider.otherwise('/dashboard');
.state('dashboard', {
url: '/dashboard',

},
views: {
// the main template will be placed here (relatively named)
'': {
templateUrl: 'views/dashboard.html',
controller: 'dashboardIndexController'
},
'headbar@dashboard': {
templateUrl: 'views/headbar.html',
controller: 'headbarController'
}
}
})
.state('dashboard.home', {
url: '/home',
templateUrl: 'views/dashboard.home.html',
controller: 'dashboardController',
})
.state('dashboard.campaigns', {
url: '/campaigns',
templateUrl: 'views/campaigns.html',
controller: 'showCampaign',

})


dashboard controller

$state.go('dashboard.home');


when i click refresh on campaigns state it redirects back to dashboard.home, which it should be as per code but how can i persist the campaigns or other nested states after reload.

Answer

Use window.localStorage.

Example

On successful landing on a page, store the current page name/url in the localStorage

window.localStorage.setItem('currentPage', window.location.pathname):

And after initialization, before redirecting to the home page, redirect to the previously stored url:

if (window.localStorage.getItem('currentPage')
    $state.go(window.localStorage.getItem('currentPage'));
else
    // go to home page normally
Comments