I've followed the examples but apparently something is wrong when adding a custom method to the resource's prototype.
app.factory('Product',function ($resource,$cacheFactory) {
var Product = $resource('/the/url/:id', {id: '@id'}),
cache = $cacheFactory('Product'),
products;
Product.prototype.all = function(){
products = cache.get('all');
if(typeof products == 'undefined'){
products = Product.query();
cache.put('all',products);
}
return products;
};
return Product;
})
In the controller I do $scope.products = Product.all(); but I get TypeError: Object function Resource(value) {
copy(value || {}, this);
} has no method 'all'
Product.prototype.all defines an instance method.
You should define it as static method Product.all = function(){...].
Only then you can call it with $scope.products = Product.all();.
I think it's because you don't actually have an instance yet. You would need to do this:
$scope.products = new Product();
// now you can run the all function
$scope.products.all()
Your other option would be to define the all() method on the service level. Instead of adding to the prototype, which is only available after new Product(), you could modify like:
app.factory('Product',function ($resource,$cacheFactory) {
var Product = $resource('/the/url/:id', {id: '@id'}),
cache = $cacheFactory('Product'),
products;
Product.all = function(){
products = cache.get('all');
if(typeof products == 'undefined'){
products = Product.query();
cache.put('all',products);
}
return products;
};
Product.prototype.$all = function () {
Product.all.call(this);
}
return Product;
})
This way you will have Product.all() on the resource and product.$all() on instances.