Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Angular.js $resource/$http factory service to handle a query string with multiple parameters from an external resource?

How could a factory $resource or $http service be created to handle a query string with multiple arbitrary parameters from an external resource? eg.

#/animals
#/animals?gender=m
#/animals?color=black
#/animals?size=small
#/animals?gender=m&color=black
#/animals?size=med&gender=f
#/animals?size=lg&gender=m&color=red

The idea is that there are buttons/inputs which the user can press to add to the current list of parameters in the query string to get a new list of animals with the desired properties in different combinations. I have tried the following but it doesn't reload or add new parameters to the existing url as desired. Also, I'm not sure if $route.current.params should be called in the controller or the factory and if that's the best way to do it.

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', $route.current.params, { query: {method: 'GET', isArray: true}});
}]);

Thanks :)

like image 880
Cliff Coulter Avatar asked Dec 26 '22 21:12

Cliff Coulter


1 Answers

If the parameters you pass in when you call the resource don't match any of the placeholders specified in the url, they're automatically converted to query string params. So you should do something like:

angular.module(Animals, ['$resource', '$route', '$location', function($resource, $route, $location) {
  return $resource('http://thezoo.com/animals', { query: {method: 'GET', isArray: true}});
}]);

and then when you try to use it, you can do:

Animals.query({size:"med",gender:'f'});

and it'll get translated to:

http://thezoo.com/animals?size=med&gender=f
like image 102
Chris Avatar answered May 06 '23 00:05

Chris