Skip to content

Instantly share code, notes, and snippets.

@ToastShaman
Forked from anonymous/index.html
Last active August 29, 2015 14:07
Show Gist options
  • Save ToastShaman/7ffc3a2a7a00a1596abe to your computer and use it in GitHub Desktop.
Save ToastShaman/7ffc3a2a7a00a1596abe to your computer and use it in GitHub Desktop.
AngularJS directive that allows you to subtract money from a total amount in pounds or percentages
<html ng-app="app">
<head>
<meta charset="utf-8">
<script src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/1.0.1/math.js"></script>
</head>
<body ng-controller="MoneyController as ctrl">
<p>
Total: <input type="number" ng-model="ctrl.total">
</p>
<p>
<number-percentage amount="ctrl.amount1" total="ctrl.total" notify="ctrl.notify"></number-percentage>
</p>
<p>
<number-percentage amount="ctrl.amount2" total="ctrl.total" notify="ctrl.notify"></number-percentage>
</p>
<p>
<number-percentage amount="ctrl.amount3" total="ctrl.total" notify="ctrl.notify"></number-percentage>
</p>
<p>
Running Total: {{ctrl.runningTotal | currency:"£ "}}
</p>
</body>
</html>
function MoneyController() {
var self = this;
self.amount1 = 0;
self.amount2 = 0;
self.amount3 = 0;
self.total = 5000;
self.runningTotal = 0;
self.notify = function() {
self.runningTotal = self.total - self.amount1 - self.amount2 - self.amount3;
}
}
function NumberPercentage() {
return {
restrict: 'E',
template: '£ <input type="number" min="0" max="{{total}}" ng-model="amount" ng-blur="amountChanged()"><input type="number" ng-model="asPercent" min="0" max="100" ng-blur="percentageChanged()">%',
scope: {
amount: '=',
total: '=',
notify: '='
},
controller: function($scope, $timeout) {
$scope.asPercent = 0;
$scope.amountChanged = function() {
if ($scope.total > 0) {
$scope.asPercent = math.round(($scope.amount * 100) / $scope.total, 3);
$timeout(function() {
$scope.notify();
});
}
};
$scope.percentageChanged = function() {
$scope.amount = math.round(($scope.asPercent / 100) * $scope.total, 3);
$timeout(function() {
$scope.notify();
});
};
$scope.$watch('total', function() {
if ($scope.total > 0) {
$scope.asPercent = math.round(($scope.amount * 100) / $scope.total, 3);
}
});
}
}
}
angular.module('app', [])
.controller('MoneyController', MoneyController)
.directive('numberPercentage', NumberPercentage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment