Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store view state in URL using Angularjs

What's the general (if there is any) consensus on storing view states as part of the URL in Angularjs and how would I go about doing it? I have a fairly complex view/route with many filters to set, tabs, etc which result in a view state.

I see the advantage for storing the state of all these view components as part of the URL in an easier navigation within the application (navigating back would restore the previous view with all selections made without loading the state from the server, which would be an alternative). Another advantage is that the view state becomes bookmarkable.

Is there a pattern that I can use for guidance? Has anyone done this before and can share some experiences? Should I stay away from storing view states in the URL?

like image 713
orange Avatar asked Nov 16 '13 07:11

orange


1 Answers

If the required data can be seriaslized into an { key, value }, then you can use $location.search() to save and retrieve this information in your controllers:

app.controller("myCtrl", function ($scope, $location, $routeParams) {
    // Load State
    var savedState = $location.search();
    allProperties.forEach(function (k) {
        if (typeof savedState[k] !== 'undefined') {
            $scope.model[k] = savedState[k];
        } else {
            $scope.model[k] = defaultValues[k];
        }
    });

    // Save the parameters
    $scope.createUrlWithCurrentState = function() {
         allProperties.forEach(function (k) {
             $location.search(k, $scope.model[k]);
         });
    });
})

Now you can call createUrlWithCurrentState with ng-change of each input element which has an ng-model and the state will be saved with each change, or you can call this function in ng-click on Create a link to this page button.

You will have to take care to keep allProperties and defaultValues updated to save all the required parameters, though.


As to whether this should be done or not, the answer depends on your use case. If you have to allow sharing of links, then there are very few alternatives to keeping state in URL.

However, some state may not be easy to serialize or the data may just be too long to save in the URL.

If you want to preserve the retrieve information only for the current session or browser, you can look at the $cookieStore or the DOM Storage API.

like image 103
musically_ut Avatar answered Oct 18 '22 06:10

musically_ut