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}
];
};
}
Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}. {{item}} </div> </div>
Pages normally have controller(s), a service can be created to share data between pages ( by injecting service in associated controllers). Like: app. factory('myService', function() { var savedData = {} function set(data) { savedData = data; } function get() { return savedData; } return { set: set, get: get } });
Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With