0

In my Angular application I want the user to be able to bookmark a particular URL, modeled with an object such as this one:

$scope.state = {
  selected : ["a", "b", "c"],
  yearOptions : [{ year: 1910, options : {color : "green"} } ]
}

a) How do I update the URL dynamically to reflect $scope.state?
b) How can I set $scope.state using any initial URL params?

2 Answers 2

1

I've written a solution for work which I am trying to open source which syncs url parameters with scope variables. What you are asking for is easy to do and is very useful when bookmarking or sharing URLs.

All you need to do is setup a $watch on the variable and use the $location.search() to set the scope variable as a url parameter. Secondly, on initial page load you will need to use $location.search() to grab the url param and set it to the scope variable. This shouldn't be hard to get working in a controller, or try writing a service to make it generic.

In order to keep the url looking nice, I used a simple dictionary to map scope variable names to url parameter names.

To get you started:

$scope.$watch('selected', function(newVal, oldVal) {
    if(newVal != oldVal) {
        $location.search('selected', newVal);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

URL length is limited to 1024 symbols, so there is no guarantee that user will be able to save any object in URL. But you can try to use JSON.stringify():

$location.search({state: JSON.stringify($scope.state)});

But it's wrong design. Much better will be if user will click on links on the page and it will change state of scope and link will be changed in nature order.

1 Comment

I agree. One thing that is possible is to work a key into the bookmarked URL. That value for the key can be stored elsewhere (database or even browser session storage, that would be interesting).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.