2014-07-12 40 views
1

我是新角度。我試圖在firebase中使用angular foreach,但它不起作用。如何做到這一點的任何指針?如何使用角色forEach與firebase

var app = angular.module('MyApp',["firebase"]); 
    app.controller('ItemCtrl', function($scope, $firebase){ 
     var ref = new Firebase("https://url.firebaseio.com"); 
     $scope.menu = $firebase(ref); 

     $scope.total = function(){ 
      var total = 0; 

      angular.forEach($scope.menu, function(item) { 

       total += item.price * item.quantity; 

      }) 

      return total; 

      }; 

    }); 

HTML

<div class=" sliding" > 
    <a href="#"class="button open" > 
    Total: {{total() | currency}} 
    </a> 
</div> 

JSON

[ 
     {"name": "Ham, Egg & Cheese CROISSAN'WICH ", 
      "quantity": 0, 
      "price": 20, 
      "description": "description", 
      "comment": "comment", 
      "imgURL": "http://url" }, 
...] 
+0

你肯定角火和火力地堡被納入正常嗎? –

+0

是的,很確定。我可以從firebase獲取數據,$ scope.menu正常工作。 – user3831592

+0

任何控制檯錯誤? – V31

回答

1

而不是試圖枚舉AngularFire我們可以聽到在火力地堡,使我們的總的任何變化。所以每次更改項目時,我們都可以自動更新總價值。

$scope.menu上,爲change事件附加$on聽衆。然後我們可以提供一個回調函數來計算$scope上的一個屬性的總數。然後在我們看來,我們不需要調用一個函數,我們可以只綁定$scope上的全部屬性。

Plunker Demo

var app = angular.module('app', ['firebase']); 

    app.constant('FBURL', 'https://<your-firebase>.firebaseio.com/items'); 
    app.service('Ref', ['FBURL', Firebase]); 

    app.controller('ItemCtrl', function($scope, $firebase, Ref) { 

    $scope.menu = $firebase(Ref); 
    $scope.total = 0; 

    // Listen for any changes in firebase 
    // 
    // The $on listener will take a event type, "change" 
    // and a callback function that will fire off for each 
    // item that has been changed. On the initial page load 
    // it will return each item at the location one at a time 
    // 
    // Remember that AngularFire automatically updates any changes 
    // for us, so we just need to get the key back from the callback 
    $scope.menu.$on('change', function(key) { 
     // the key is the object's key in Firebase 
     var item = $scope.menu[key]; 
     $scope.total += item.price * item.quantity; 
    }); 

    }); 

<div class="sliding"> 
    <a href="#" class="button open"> 
    Total: {{ total }} 
    </a> 
</div> 
+0

它的作品:),非常感謝! – user3831592

+0

呃....我應該怎麼做,如果我想修改firebase中的數據,比如增加數量。 – user3831592

+0

太容易了!問另一個問題,我會在評論中回答這些問題要容易得多。 –