Angular $ resource自定义方法

ola*_*nod 5 angularjs

我已经按照这些示例进行了操作,但在向资源原型添加自定义方法时显然有些问题.

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;
    })
Run Code Online (Sandbox Code Playgroud)

在控制器我做,$scope.products = Product.all();但我得到

TypeError: Object function Resource(value) {
    copy(value || {}, this);
} has no method 'all'
Run Code Online (Sandbox Code Playgroud)

Ste*_*wie 12

Product.prototype.all 定义实例方法.

您应该将其定义为静态方法Product.all = function(){...].

只有这样你才能调用它$scope.products = Product.all();.

  • 可以理解的.这些简单的错误通常很容易在复杂的项目中或在漫长的日子里滑过. (3认同)