Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  175] [ 2]  / answers: 1 / hits: 18517  / 11 Years ago, sun, september 8, 2013, 12:00:00

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}
];

};
}

More From » angularjs

 Answers
27

I would recommend making a grandTotal function on your $scope and then binding that, like this:



http://jsfiddle.net/XMTQC/



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.


[#75834] Thursday, September 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leifw

Total Points: 88
Total Questions: 103
Total Answers: 103

Location: France
Member since Thu, May 6, 2021
3 Years ago
;