Simple Interest Calculator directive
There is dependency of variable names. This should be in sync between the directive declaration and in the callback function call.
by Taleeb Anwar
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<body ng-app="SimpleInterestApp" ng-controller="simpleCtrl">
<div class="container">
<div class="row">
<si-calc on-calc="onInterestCalculated(interest, newPrinciple)" />
</div>
<div class="row">
Calculated Interest: {{Int|currency}}
</div>
<div class="row">
Calculated Amount: {{Amt|currency}}
</div>
</div>
</body>
JavaScript
angular.module('SimpleInterestApp', [])
.controller('simpleCtrl', function($scope) {
$scope.Int = 0;
$scope.Amt = 0;
$scope.onInterestCalculated = function(int, P) {
$scope.Int = int;
$scope.Amt = P;
};
})
.directive('siCalc', function() {
return {
restrict: 'E',
template: '<input type="text" ng-change="onChange(this.P,\'P\')" ng-model="P" class="col-xs-4 col-sm-4 col-md-4 col-lg-4" placeholder="Principle" />' +
'<input type="text" ng-change="onChange(this.R, \'R\')" ng-model="R" class="col-xs-4 col-sm-4 col-md-4 col-lg-4" placeholder="Rate" />' +
'<input type="text" ng-change="onChange(this.T,\'T\')" ng-model="T" class="col-xs-4 col-sm-4 col-md-4 col-lg-4" placeholder="Time" />' +
' <input type="button" value="Calculate" ng-click="Calc()" class="btn-primary btn-small" /> ',
scope: {
onCalc: '&'
},
link: function(scope, elem, attrs) {
scope.onChange = function(n,key) {
if (!scope.isNumeric(n)) {
scope[key] = '';
}
};
scope.isNumeric = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
scope.Calc = function() {
if (scope.isNumeric(scope.P) && scope.isNumeric(scope.R) && scope.isNumeric(scope.T)) {
var I = (scope.P * scope.R * scope.T) / 100;
var newP = parseFloat(scope.P) + I;
scope.onCalc({
interest: I,
newPrinciple: newP
});
}
}
}
}
});