Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save $location parameters state AngularJS

How do I save URL parameters state throughout lifecycle of application using pushState?

  1. Page load.
  2. Go to "/search" via href
  3. submitSearch() through filter fields where $location.search(fields)
  4. Go to "/anotherPage" via href
  5. Go back to "/search" via href
  6. Search paramters are set back to what they last were.

Is this a built in feature somewhere?

If not what's the best way to go about this?

like image 202
Dan Kanze Avatar asked Mar 23 '23 03:03

Dan Kanze


1 Answers

If you're planning on a mostly single page website through pushState, you might want to get an intimate understanding of $routeProvider (http://docs.angularjs.org/api/ngRoute.%24routeProvider).

To go further down the rabbit hole, I would recommend looking at the ui-router module: (https://github.com/angular-ui/ui-router). $stateProvider (from ui-router) and $routeProvider work very similar, so sometimes the ui-router docs can give insights that you can't find in the poor documentation of the $routeProvider.

I reccomend going through the five page ui-router documentation (https://github.com/angular-ui/ui-router/wiki) page by page.

After all that preamble, here's the practical: you would set up a factory that holds history data and use the controller defined in your $routeProvider/$stateProvider to access and manipulate that data.

Note: the factory is a service. A service is not always a factory. The namespace goes:

angular.module.<servicetype[factory|provider|service]>. 

This post explains the service types: https://stackoverflow.com/a/15666049/2297328. It's important to remember that they're all singletons.

Ex:

var myApp = angular.module("myApp",[]);
myApp.factory("Name", function(){
  return factoryObject
});

The code would look something like:

// Warning: pseudo-code
// Defining states
$stateProvider
  .state("root", {
    url: "/",
    // Any service can be injected into this controller.
    // You can also define the controller separately and use
    // "controller: "<NameOfController>" to reference it.
    controller: function(History){
      // History.header factory
      History.pages.push(History.currentPage);
      History.currentPage = "/";
    }
  })
  .state("search", {
    url: "/search",
    controller: function(History, $routeParams) {
      History.lastSearch = $routeParams
    }
  });

app.factory('<FactoryName>',function(){
  var serviceObjectSingleton = {
    pages: []
    currentPage: ""
    lastSearch: {}
  }
  return serviceObjectSingleton
})

If you're wondering what the difference between $routeProvider and $stateProvider is, it's just that $stateProvider has more features, mainly nested states and views... I think.

like image 97
Kirk Werklund Avatar answered Apr 03 '23 00:04

Kirk Werklund