bristophocles
bristophocles

Reputation: 143

GET Params in AngularJS Route URL

In my Angular application, I am showing a list of inventory items. On this page, there is a form to filter or perform a search. This form submits to the same url for the current route template/page, but appends get parameters in the url to perform the filter/search. i.e. /#/inventories, and /#/inventories?keywords=widgetname

Here is the basic route...

myApp.config(function($routeProvider) {
    $routeProvider

    .when('/inventories', {
        templateUrl: '/inventories.html',
        controller: 'inventoriesController'
    })
});

I know I could do something like the example below for a route with a variable parameter like /#/inventories/12 for a particular inventory resource, like so...

.when('/inventories/:inventory_id', {
    templateUrl: function(params) { return '/inventories/' + params.inventory_id + '.html'},
    controller: 'inventoryController'
})

But what would I do for a route like /#/inventories?keywords=widgetname&warehouse=1&min_qty=5 which contains all of my filter parameters in the url string? How do I accommodate url GET parameters in the route?

I tried something like this, but doesn't work...

.when('/inventories?:get_params', {
    templateUrl: function(params) { return '/inventories?' + params.get_params},
    controller: 'inventoryController'
})

I know that I could try using $http service and work with json by tying an array of results on the scope to an ng-repeat or something like that, but I would rather just refetch the template returned with the filtered results from url. Is this possible?

Upvotes: 0

Views: 484

Answers (1)

just95
just95

Reputation: 1099

You should be able to access the query parameters from the params attribute just like regular route parameters. If you have the URL /inventories?keywords=widgetname the value of params.keywords should therefore be 'widgetname'.

I wrote a fiddle to demonstrate this. I tested only with template but I am sure it will work the same with templateUrl.

Upvotes: 1

Related Questions