Reputation: 13
I'm new to angular. I'm attempting to use angular foreach with firebase, but it didn't work. Any pointers on how to do this?
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" },
...]
Upvotes: 1
Views: 1155
Reputation: 32604
Rather than trying to enumerate over AngularFire we can listen to any changes in Firebase that make up our total. So every time an item is changed we can update the total value automatically.
On the $scope.menu
, attach an $on
listener for the change
event. Then we can provide a callback function that calculates the total to a property on $scope
. Then in our view we won't have to call a function we can just bind the total property on $scope
.
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;
});
});
The View
<div class="sliding">
<a href="#" class="button open">
Total: {{ total }}
</a>
</div>
Upvotes: 1