2014-07-12 39 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

太容易了!问另一个问题,我会在评论中回答这些问题要容易得多。 –