I have a input to show a formatted number. Normally, when it has no focus, it should show a formmatted string, e.g. \'$50,000.00\'. But when it has focus, it should show the
angular.module('app', [])
.controller('TestCntrl', function TestCntrl($scope) {
$scope.value = 50000.23;
})
.directive('numberFormatter', ['$filter', function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
scope: { 'decimal': '=decimal' },
link: function (scope, element, attr, ngModel) {
ngModel.$parsers.push(whatToSet);
ngModel.$formatters.push(whatToShow);
element.bind('blur', function () {
element.val(whatToShow(ngModel.$modelValue, scope.decimal))
});
element.bind('focus', function () {
element.val(ngModel.$modelValue);
});
function whatToSet(str) {
var num = 0
var numbe = num !== undefined ? num : 0;
var strr = str.toString();
strr = strr.replace(',', '.');
numbe = parseFloat(strr);
return numbe;
}
function whatToShow(num) {
if (num) {
return '$' + $filter('number')(num, scope.decimal);
} else {
return '';
}
};
}
};
}]);
value in the model: {{value}}