用输入字段中的点替换逗号

时间:2014-01-29 09:33:12

标签: angularjs

欧洲国家/地区输入十进制数字时使用逗号(,)代替点(。)。因此,当用户输入输入时,我想用逗号替换点符号。我知道input = number这样做但我需要支持IE。

我想指令是最好的吗?我尝试了下面的代码。但它失败了。

  .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;
        });
      }
    }
  });

转换变量是正确的。但是输入框中的值不会改变。所以我猜attrs.ngModel =转换,是错的?

4 个答案:

答案 0 :(得分:2)

我认为没有必要像指令那样做。

说你的模板是

<input ng-model='someModel'>

在你的控制器中,

$scope.$watch('someModel',function(newVal){
    $scope.someModel = newVal.replace(/,/g,'.');
})

ng-model是一种双向绑定,因此它应该可以正常工作

答案 1 :(得分:2)

通过指令:

.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 :(得分:1)

var mystring =“this,is,a,test”
mystring = mystring.split(',')。join('');

mystring contains ==&gt; “这是一个考验”

答案 3 :(得分:1)

在你的模板中:

  <input type="text" ng-model="someModel" replace-comma >

在你的模块中:

.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);
    }
};});