Replace the comma with a dot in the input field

European countries use a comma (,) instead of a period (.) When they enter decimal numbers. Therefore, I want to replace the semicolon when users enter input. I know input = number does this, but I need IE support.

Think directive is best to do this? I tried the code below. But he 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 conversion variable is correct. But the value does not change in the input field. So, I think attrs.ngModel = convert, isn’t it?

+4
angularjs
source share
4 answers

Through the directive:

 .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, '.')); } }) } } }); 
+2
source share

I think there is no need to do this as a directive.

say your template

 <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

+1
source share

var mystring = "this, is, a, test"
mystring = mystring.split (','). join ('');

mystring contains ==> "this is a test"

+1
source share

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); } };}); 
+1
source share

All Articles