Angular $ resource custom method

I followed the examples, but apparently something is wrong when you add your own method to the resource 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'
+5
source share
2 answers

Product.prototype.all defines an instance method.

You must define it as a static method Product.all = function(){...].

Only then can you call it with $scope.products = Product.all();.

+12
source

I think because you don’t have a copy yet. You will need to do this:

$scope.products = new Product();
// now you can run the all function
$scope.products.all()

Another option is to define the all () method at the service level. Instead of adding to the prototype, which is only available after the new Product (), you can change it as:

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 () for the resource and product. $ all () for instances.

+3

All Articles