Tamlyn
Tamlyn

Reputation: 23602

Maintain Angular $scope on navigation

I have an Angular app with several controllers. I would like each controller to maintain its state even when the user navigates to another controller and back again. Essentially I want each view to load up just as the user last saw it (unless they navigate away from the app entirely or refresh etc.).

I understand how to share state between controllers using a service but this is not what I want. I could create a new service for every controller or put everything on the $rootScope but it seems wrong.

What is the recommended way to do this?

Upvotes: 0

Views: 989

Answers (1)

Nate-Wilkins
Nate-Wilkins

Reputation: 5502

I would store any persistent data in the $cookieStore and maybe even encapsulate it in a service to avoid remembering what the interface to the cookie actually is. Here's an example:

var app = angular.module('app', [
    'ngRoute',
    'ngCookies'
]);

app.service('ticketService', function ($cookieStore) {
    this.getTicket = function () {
        var ticket = $cookieStore.get('currentTicket');
        // Check server for ticket? (additional business logic)
        return ticket;
    };

    this.setTicket = function (ticket) {
        // Validate correct ticket? (additional business logic) 
        $cookieStore.set('currentTicket', ticket);
    };
});

app.controller('ticketController', function ($scope, ticketService) {
    var defaultTicket = { 
        name: '',
        description: ''
    };

    $scope.ticket = ticketService.getTicket() || defaultTicket;

    $scope.$watch('ticket', function (oldValue, newValue) {
        if (oldValue === newValue) { return; }
        ticketService.setTicket(newValue);
    });
});

Upvotes: 1

Related Questions