Hi,
Just starting to learn AngularJS and so far I love it!
I ran into my first real challenge whereby I have a requirement to allows users to input values into an input field - and while they type, the input value should be modified with thousand separators (in my case a dot for european currency format).
So basically, the input should have the separator, but the corresponding model should NOT have the dot (but only the clean value).
I have been thinking about multiple approaches but I keep running into scoping issues and the fact that the view representation is different from the model. So far, I came up with a directive that kind of does what I need, but still has some issues.
The view looks like this in it simplest form:
<input thousand-separator="\." type="text" data-ng-model="testvalue"/>And the Directive:
.directive('thousandSeparator', [ '$timeout', function($timeout) {
return {
require: 'ngModel',
link: function(scope, element, attrs, controller){
var sep = attrs.thousandSeparator || ".";
var model = attrs.ngModel;
var doReplace = function(){
var curValue = element.val();
var replace = new RegExp(sep, 'g');
var cleanValue = curValue.replace(replace, "");
// Create dotted value from clean
var x1 = cleanValue + '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
element.val(x1);
scope.$apply(function () {
controller.$setViewValue(cleanValue);
});
}
element.on('keyup', function(){
doReplace();
});
element.on('blur', function(){
doReplace();
});
// trigger for existing model values
$timeout(doReplace,1);
}
}
}])So this kinda works - check the Plunker here:
http://plnkr.co/edit/jY3itHHtHWTJmbDsoInp?p=previewIt shows the dotted value in the input (while you type) and the testvalue model updates (slightly delayed).
I have my doubts of this is the correct way of doing it. It seems slightly hacky to me so I'm looking for some feedback or different approaches on how to do this.
Also, I have problem if I put this directive in an NgRepeat loop - the model no longer updates then?
See plunker for that issue here:
http://plnkr.co/edit/0berlPHhnFymCdsAGrz7?p=previewAny input appreciated!