Skip to content Skip to sidebar Skip to footer

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 man

Solution 1:

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 Statevar 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.

Post a Comment for "Store View State In Url Using Angularjs"