2013-03-04 22 views
0

我有一個ProdCache服務用於緩存產品數組。

... 
var products = ProdCache.get('all'); 
if(typeof products == 'undefined'){ 
    products = Product.query(); 
    ProdCache.put('all',products); 
} 

如果我將產品放在產品範圍上,產品按預期顯示,但我只需要顯示少量產品。
我嘗試:

$scope.related = (function(){ 
    var res = []; 
    if(products.length>0){ 
     for (var i = 0, key; i < 3; i++) { 
      key = Math.floor(Math.random() * products.length); 
      res.push(products[key]); 
     } 
    } 
    return res; 
})(); 

該功能不會工作的第一時間,因爲XHR請求正在處理和返回的數據不具有反應性。

回答

1

正確的方法是使用過濾器文檔herehere

假設你寫的過濾器是模擬的,你需要一個複雜的過濾器,你就必須在$scope創建過濾器功能,並在ng-repeat表達引用它:

$scope.isRelated = function isRelatedFilter(item) { 
    // if return is true, the item is included. 
    return item.someProperty === 'someCriteria'; 
} 
<span ng-repeat="product in products | filter:isRelated">...</span> 

someCriteria可能成爲另一個$ scope/controller屬性或由服務定義。如果您需要自定義參數,則無法使用filter過濾器,並應自行創建。看看文檔。

0

沒有用於綁定的HTML代碼,要確定如何使用$ scope.related函數有點困難。然而,如果你遇到的唯一問題是,當數據從xhr請求返回時,UI不會更新,那麼很可能您的$ digest階段已經結束,因此綁定到$ scope.related不是導致該功能重新啓動,直到下一個$摘要階段。

這可能會上班,以處理您遇到的問題:

... 
var products = ProdCache.get('all'); 
if(typeof products == 'undefined'){ 
    products = Product.query(); 
    ProdCache.put('all',products); 
    // Add this line to force re-digest if needed 
    if(!$scope.$$phase) $scope.$digest(); 
} 

雖然沒有看到HTML,我不知道,這將解決您的問題。如果不是的話,發佈一個活塞,這樣我們可以更好地看到問題。