Reputation: 409
I am new to Angular and have a basic question about ng-bind that I couldn't find in the documentation. My scenario is based the shopping cart app in the O'Reily Angular.js book and I cannot seem to get ng-bind to work.
Desired output: I need to modify my controller function so I can show my updated $scope.items array elements in a 'Grand Total' span.
Here is the function:
function CartController($scope) {
$scope.items = [
{title: 'Software', quantity: 1, price: 1399.95},
{title: 'Data Package (1TB)', quantity: 1, price: 719.95},
{title: 'Consulting (per hr.)', quantity: 1, price: 75.00}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
},
$scope.reset = function(index) {
$scope.items = [
{title: 'Software', quantity: 0, price: 1399.95},
{title: 'Data Package (1TB)', quantity: 0, price: 719.95},
{title: 'Consulting (per hr.)', quantity: 0, price: 75.00}
];
};
}
Upvotes: 5
Views: 18432
Reputation: 20073
I would recommend making a grandTotal
function on your $scope
and then binding that, like this:
HTML
<div ng-app ng-controller="CartController">
Grand Total: <span>{{grandTotal()}}</span>
<br/>
Grand Total: <span ng-bind="grandTotal()"></span>
<br/>
</div>
JavaScript
$scope.grandTotal = function () {
return $scope.items.reduce(function (p, c) {
return p.price || p + c.price;
});
};
You can also use interpolation (instead of ngBind
) as indicated in the first span.
Upvotes: 13