Skip to content

Instantly share code, notes, and snippets.

@maxehmookau
Created October 15, 2013 20:22
Show Gist options
  • Save maxehmookau/6998049 to your computer and use it in GitHub Desktop.
Save maxehmookau/6998049 to your computer and use it in GitHub Desktop.
Angular Step One
function CartController($scope) {
$scope.items = [
{ name: 'Fish', quantity: 0, price: 20.00 },
{ name: 'Chips', quantity: 0, price: 0.20 }
];
$scope.total = function() {
var total = 0;
for(var i = 0; i < $scope.items.length; i++) {
total = total + ($scope.items[i].quantity * $scope.items[i].price);
}
return total;
}
}
<!DOCTYPE html>
<html ng-app>
<head>
<title></title>
</head>
<body>
<div ng-controller="CartController">
<div ng-repeat="item in items">
<span>{{item.name}} ({{item.price | currency}} each)</span>
<span>Quantity: <input ng-model="item.quantity"></span>
<span>Total: {{ item.quantity * item.price | currency }}</span>
</div>
<span>Total: {{total() | currency}}</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="controllers.js"></script>
</body>
</html>
@athieriot
Copy link

If I might add a little something :)

I would avoid the "for loop" in Javascript if you can do without.
Even in vanilla JS there is a lot of nice functional features past a certain IE version.
(It's even better if you have Underscore of equivalent)

First, it enforce immutability and JS can be more efficient than just looping an array. (JS engine can do better optimisations)

In this case, you can use reduce:

  var total = $scope.items.reduce(function(previous, next) {
     return previous + (next.quantity * next.price)
  }, 0);

P.S: More infos here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

PS: You can also ask me to shut up :p

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment