Reputation: 4244
European countries uses a comma-sign (,) instead of a dot (.) when they enter decimal numbers. So I want to replace the dot sign with a comma when users enter input. I'm aware that input=number do this but I need support for IE.
I guess directive is the best to do this? I gave it a try with the code below. But it fails.
.directive('replaceComma', function(){
return {
restrict: 'A',
replace: true,
link: function(scope, element, attrs){
scope.$watch(attrs.ngModel, function (v) {
var convert = String(v).replace(",",".");
attrs.NgModel = convert;
});
}
}
});
The convert variable is correct. But the value does not change in the input box. So I guess attrs.ngModel = convert, is wrong?
Upvotes: 4
Views: 18224
Reputation: 183
In your template:
<input type="text" ng-model="someModel" replace-comma >
in your module :
.directive('replaceComma', function(){
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/,/g, '.')
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(fromUser);
}
};});
Upvotes: 1
Reputation: 1737
.directive('replacecomma', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
scope.$watch(attrs.ngModel, function (newVal) {
if (newVal !== undefined && newVal !== null) {
ngModelCtrl.$setViewValue(String(newVal).replace(/,/g, '.'));
element.val(String(newVal).replace(/,/g, '.'));
}
})
}
}
});
Upvotes: 2
Reputation: 11872
var mystring = "this,is,a,test"
mystring = mystring.split(',').join(' ');
mystring contain ==> "this is a test"
Upvotes: 1
Reputation: 783
I think there is no need to do this like a directive.
say your template is
<input ng-model='someModel'>
in your controller,
$scope.$watch('someModel',function(newVal){
$scope.someModel = newVal.replace(/,/g,'.');
})
ng-model is a two-way binding, so it should work
Upvotes: 4