Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $resource custom method

Tags:

angularjs

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'
like image 544
olanod Avatar asked Mar 04 '13 14:03

olanod


2 Answers

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();.

like image 118
Stewie Avatar answered Oct 09 '22 18:10

Stewie


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.

like image 29
Jason Aden Avatar answered Oct 09 '22 17:10

Jason Aden