我是新手。我正在尝试在firebase中使用angular foreach,但是没有用。关于如何执行此操作的任何指示?
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" },
...]
最佳答案
无需尝试枚举AngularFire,我们可以收听Firebase中构成我们总数的任何更改。因此,每次更改项目时,我们都可以自动更新总价值。
在$scope.menu
上,为$on
事件附加一个change
侦听器。然后,我们可以提供一个回调函数,用于计算$scope
上某个属性的总数。然后,在我们看来,我们不必调用一个函数,只需绑定$scope
上的total属性即可。
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>