2016-08-17 25 views
0

我正嘗試在Angular和Node中構建自己的購物車系統。我的控制器處理mongo數據庫中的用戶手推車和本地存儲中的手推車(如果用戶沒有帳戶)。現在,我爲我的購物車控制器創建了一種方法,可以從本地存儲和數據庫中刪除購物車項目。我的角度觀看的對象。Angular如何監視Scope變量的變化

$scope.lineItems 

用於使用物品填充購物車。現在我可以成功獲取更新的購物車,但我需要刷新我的頁面。通過觸發更新範圍的函數來更新範圍的最好方法是什麼?

代碼:

if (token) { 
    var payload = authService.parseToken(token); 
    dataService.getCart(payload._id).then(function (resolve){ 
     if (resolve.data){ 
     $scope.lineItems = resolve.data; 

     $scope.deleteLineItem = function(lineitem){ 
      dataService.deleteLineItem([lineitem.lineItemID, payload._id]); 
     } 
     } 
    }, function(reason){ 
     console.log(reason); 
    }); 
} else { 
    if (dataService.retrieveLocal('localCart')){ 
     $scope.lineItems = dataService.retrieveLocal('localCart'); 

     $scope.deleteLineItem = function(lineitem){ 
      var cart = dataService.retrieveLocal('localCart'); 
      var updatedCart = cart.filter(function(item){ 
       if (lineitem.lineItemID != item.lineItemID){ 
        return item 
       } 
      }) 
      dataService.storeToLocal('localCart', updatedCart); 
     } 
    } 
} 

回答

0

我強烈建議您不要使用AngularJS Watcher由於重負載的成本,一般來說,在您的應用程序儘量減少您的觀察者(定時器)。 此外,在您的情況下,您不需要使用watcher,因爲當您使用LocalStorage時,不需要再次在所有瀏覽器選項卡中刷新頁面,實際上您的購物車項目只是看你的$localStorage.lineItems而不是$ scope。 lineItems和自$ localStorage.lineItems更新後,所有瀏覽器選項卡將自動更新。 在一個選項卡中,您將觸發基於點擊事件等的請求和服務器端處理,然後在響應中更新您的localStorage變量($localStorage.lineItems),因此您的內容將始終更新。