I'm trying to create a directive for an input element. When a number is entered I want to update the input value on the blur event by adding zeros like '12' -> '0012'. I have a parameter passed to directive to specify the length of the result number for example if the length of the number is 6 and the user enters 123 the result is 000123
I have created a directive, but after the blur event, the render view works but it does not change the ng-model
value
app.directive('addZeros', function() {
return {
restrict: 'A',
scope: {
addZeros: '=addZeros'
},
require: '?ngModel',
link: function(scope, element, attrs, modelCtrl) {
var addZeroOK = false;
modelCtrl.$parsers.push(function(inputValue) {
var num = parseInt(inputValue, 10);
num = '' + num;
var clean = num.replace(/[^0-9]/g, '');
if (inputValue.length <= scope.addZeros) {
scope.addZeros = parseInt(scope.addZeros, 10);
if (isNaN(clean) || isNaN(scope.addZeros)) {
return inputValue;
}
element.bind('blur', function(event) {
if (clean.length > 0) {
addZeroOK = true;
while (clean.length < scope.addZeros) {
clean = '0' + clean;
}
}
scope.$apply(function() {
modelCtrl.$setViewValue(clean);
modelCtrl.$render();
return clean;
})
});
if (addZeroOK == false) {
modelCtrl.$setViewValue(clean);
modelCtrl.$render();
return clean;
}
} else {
var str = inputValue.slice(0, -1);
modelCtrl.$setViewValue(str);
modelCtrl.$render();
return str;
}
});
}
};
});