Created
October 15, 2013 20:22
-
-
Save maxehmookau/6998049 to your computer and use it in GitHub Desktop.
Angular Step One
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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