Skip to content

Instantly share code, notes, and snippets.

@ladyjer
Created March 15, 2016 21:41
Show Gist options
  • Save ladyjer/31fdc95ee67715c69170 to your computer and use it in GitHub Desktop.
Save ladyjer/31fdc95ee67715c69170 to your computer and use it in GitHub Desktop.
Excel-like sum of HTML input fields using AngularJS
<!DOCTYPE html>
<html lang="en">
<head>
<title>Excel like</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<h1>Excel like</h1>
<table ng-app="excel" ng-controller="excelController">
<thead>
<tr><td>Numbers</td></tr>
</thead>
<tbody>
<tr>
<td><input type="number" name="amount[]" ng-model="amount.id1"/></td>
</tr>
<tr>
<td><input type="number" name="amount[]" ng-model="amount.id2"/></td>
</tr>
<tr>
<td><input type="number" name="amount[]" ng-model="amount.id3"/></td>
</tr>
<tr>
<td><input type="number" name="amount[]" ng-model="amount.id4"/></td>
</tr>
<tr>
<td><input type="number" name="amount[]" ng-model="amount.id5"/></td>
</tr>
<tr>
<td><input type="number" name="amount[]" ng-model="amount.id6"/></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total: <span ng-bind="sum()"></span></td>
</tr>
</tfoot>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
angular.module('excel',[]).
controller('excelController', ['$scope', function($scope){
$scope.sum = function() {
totale = 0.0;
angular.forEach($scope.amount,function(value,index){
if (value == null) {
// Do nothing.
} else {
totale += parseFloat(value);
}
})
return totale.toFixed(2);
};
}]);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment