2013-03-04 63 views
5

我跟着例子,但顯然增加了自定義的方法對資源的原型時,什麼是錯的。

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; 
    }) 

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

+0

您能否提供添加到$ resource的原型的示例的鏈接?我不記得曾經看到過。 – 2013-03-04 14:55:41

回答

12

Product.prototype.all限定一個實例方法。

你應該把它定義爲靜態方法Product.all = function(){...]

只有這樣,你可以用$scope.products = Product.all();調用它。

+0

謝謝,我不知道爲什麼在這一點上,我犯這樣的錯誤XD – olanod 2013-03-04 15:27:54

+3

可以理解。這些簡單的錯誤在複雜的項目中或在漫長的日子裏通常很容易就會漏掉。 – Stewie 2013-03-04 17:49:44

3

我想這是因爲你沒有真正有一個實例呢。您需要執行此操作:

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

您的其他選項是在服務級別上定義all()方法。相反增加了原型,這是隻有在新產品()提供的,你可以修改,如:。

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; 
}) 

這樣你會對資源Product.all()和產品$所有()上實例。

+0

注入資源時不是定義服務的一個實例嗎?我如何在不實例化服務的情況下做到這一點? – olanod 2013-03-04 15:18:44

+0

當它被注入時,你會得到服務的一個實例,是的,但不是資源的一個實例。更新答案以包括如何調用服務級別的all()方法。 – 2013-03-04 15:30:27