我是棱角分明的新人。我尝试使用角形的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 :(得分:1)
我们可以收听构成总数的Firebase中的任何更改,而不是尝试枚举AngularFire。因此,每次更改项目时,我们都可以自动更新总值。
在$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>