A few things:
- This probably isn't the best use of
$resource
. $http
would be preferrable in this scenario, because you're not really dealing with a RESTful web service. You're apparently dealing with GET
s on .json files. Using $resource
will instantiate a bunch of extra functions and overhead you don't need and can't use.
- The best place to filter the results you're getting back would be at the server. I know you can't really do that with a .json file, but it's worth mentioning.
- This really isn't an issue with $resource or even Angular, so much as it is an issue with JavaScript, what you want to do is get a subset of objects from an array.
All of that said... if you must do this using $resource, you could do something like the following pseudo-code:
// a factory to create your Park resource service.
app.factory('Park', ['ngResource', function($resource) {
//your Park resource constructor.
var Park = $resource('locations/:categoryId.json', {}, {
query: {method:'GET', params:{categoryId:'categories'}, isArray:true}
});
//a "static" function on Park to filter results.
Park.filter = function(parks, predicate) {
var results = [];
for(var i = 0; i < parks.length; i++) {
var park = parks[i];
if(predicate(park)) {
results.push(angular.copy(park));
}
}
return results;
};
//return the constructor
return Park;
}]);
// a controller example to consume your service.
app.controller('MainCtrl', function($scope, Park) {
// get all parks in category 123
var allParks = Park.query({categoryId: 123});
// filter the parks down to the ones named "Hooterville Park"
$scope.parks = Park.filter(allParks, function(park) {
return park.name === 'Hooterville Park';
});
});
The thing is, $resource is made to be used with a RESTful resource like so:
// create a basic resource.
var Foo = $resource('/Foo/:id');
// get and update one item.
var foo = Foo.get(123, function() {
foo.name = 'Test';
foo.email = 'blah@sample.com';
foo.$save();
});
// create a new item.
var foo2 = new Foo();
foo2.name = 'New guy';
foo2.email = 'new@guy.com';
foo.$save();
// get and update a bunch of items.
var foos = Foo.query();
for(var i = 0; i < foos.length; i++) {
var fooItem = foos[i];
fooItem.name = 'Foo ' + i;
fooItem.$save();
}
So unless you're going to do that stuff, I'd say go ahead and just use $http.