title: History API/Angular: how to go back to predetermined URL
body: <p>I have a requirement within my Angular app which uses the Angular UI Router, to go back from one screen (URL) to a previously visited screen (URL). There are several screens (URLs) where it's possible to visit the destination page. It's not quite as straight forward as a simple <code>history.back()</code> operation though` because I have several interim states that can occur in any order and any number. To get around this I have implemented a wrapper around the Angular $location service, like so:</p>
  
  <pre><code>(function () {
      'use strict';
      angular
          .module('myApp')
          .factory('locn', ['$location', '$state',
              function ($location, $state) {
                  var states = [];
                  return {
                      go: function (url) {
                          $location.path(url);
                      },
                      pushandgo: function (state, params) {
                          states.push({ name: $state.current.name, params: $state.params });
                          $state.go(state, params);
                      },
                      push: function (url) {
                          states.push(url);
                      },
                      pop: function () {
                          var state = states.pop();
                          $state.go(state.name, state.params);
                      },
                      search: function (searchDict) {
                          $location.search(searchDict);
                      }
                  };
              }]);
  
  })();
  </code></pre>
  
  <p>As you can see, this stores the state in a javascript local variable of the <code>locn</code> service. I can call <code>pushandgo</code> and that means when I subsequently call <code>pop</code> I can return to the page I came from (regardless of what page that was).</p>
  
  <p>This works OK, until the user refreshes the page when they are on the destination page.</p>
  
  <p>The states array is recreated loosing all previously pushed states.</p>
  
  <p>I'm struggling to come up with a nice solution to this other than using cookies or local storage (yuck).</p>