Skip to content

Instantly share code, notes, and snippets.

Created October 9, 2014 22:01
Show Gist options
  • Save anonymous/6b22687b84534450cf3d to your computer and use it in GitHub Desktop.
Save anonymous/6b22687b84534450cf3d to your computer and use it in GitHub Desktop.
A Pen by Captain Anonymous.
<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