Seeking to develop a straightforward Angular directive for handling currency input. The objective is to have it operate as a float in the model while showing two decimal places to the user.
The code implemented for this purpose is as follows:
// Currency Input (Element Directive)
// Basic text box ensuring 2 decimal place numeric input
// Usage:
// <currency
// ng-model: string, angular model binding, optional
// ></currency>
directives.directive('currency', function() {
return {
require: 'ngModel',
restrict: 'E',
replace: true,
transclude: true,
template: '<span class="currency"><input type="text" ng-model="text" ng-transclude /></span>',
scope: {
ngModel: '=amount'
},
link: function($scope) {
return function($scope, elem, attrs, ctrl) {
$scope.$watch("text", function(newVal) {
$scope.amount = parseFloat(newVal);
console.log();
console.log("text changed, recalculating amount");
console.log("Successfully converted", newVal, "into", $scope.amount);
});
$scope.$watch("amount", function(newVal) {
$scope.text = newVal.toFixed(2);
console.log();
console.log("amount changed, recalculating text");
console.log("Successfully converted", newVal, "into", $scope.text);
});
}
},
controller: function ($scope) {
$scope.text = "test";
$scope.amount = 0;
grabScope = function() { //Debug function to allow global access to this scope
return $scope;
}
}
};
});
When implementing this directive, a textbox is generated with the text "test". However, editing within the textbox fails to update $scope.text and subsequently does not trigger the watches or update the model.
I've been pondering over this issue for some time now, but I suspect there might be a simple mistake on my part. Any insights?
Thank you,
YM