0

I'm having an issue with AngularJS and URLS. When I press the back/forward buttons in the browser I want my models to update accordingly. As you can see from this page: http://www.networkwestmidlands.com/whats-on/#params?when=Today&what=Events&where=birmingham

It pulls the variables from the url(a getter function that I set as my default value for x model if available) and sets them to the model for each search filter. If you start updating the filters the URL will also update(this calls a function on ng-change), and refreshing or sharing the url will load the page with all the models predefined from the url.

The trouble i'm having is that the view/controller doesn't update/refresh when pressing the back/forward buttons.

An example of how I define my model on page load in my controller:

vm.type = getFromURL('what=') || 'Events';

function getFromURL(filterName){
            var url = $location.url();
            // if there is already a hash in the url
            if(url && url.indexOf('params?') >= 0){
                // If the search param already exists
                if(url.indexOf(filterName) >= 0){
                    // Split url at already existing search param
                    var searchParams = url.split(filterName)[1];
                    // if there is still an '&' in the url do something
                    if(searchParams.indexOf('&') >= 0){
                        // split at the '&' and get rid of anything after it(other search params)
                        var singledParam = searchParams.split('&')[0];
                        return singledParam;
                    }else{
                        return searchParams;
                    }
                // If the suggested search param doesn't exist
                }
            }
        }
Dayle Salmon
  • 271
  • 2
  • 11
  • the thing is, when you change your `$location.url()` you are not navigating to it! You're just running some arbitrary angular code. This means you're not sticking anything in the broswer history! What you actually need to do is force a page reload! So it gets stored in the history – Callum Linington Jul 19 '16 at 14:10
  • You should consider using some form of routing, like ui.router – jbrown Jul 19 '16 at 14:11
  • Have a look : http://stackoverflow.com/a/201406/5119391 – Deepika Jul 19 '16 at 14:11

1 Answers1

0

I ended up using: $location.url(url).replace(); which worked as required.

Dayle Salmon
  • 271
  • 2
  • 11