Angularjs 在表单控件上添加新解析器

Angularjs 在表单控件上添加新解析器,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我正在尝试为输入编写一个自定义指令,该指令将修改模型,这样,如果用户在输入中键入一个数字“25000”,模型将以整数形式的值“25000”结束 到目前为止,我有以下代码: <div ng-app="myApp"> <div ng-controller="SomeController"> <input type="number" name="some-field" ng-model="numericValue" integer /> </d

我正在尝试为输入编写一个自定义指令,该指令将修改模型,这样,如果用户在输入中键入一个数字“25000”,模型将以整数形式的值“25000”结束

到目前为止,我有以下代码:

<div ng-app="myApp">
  <div ng-controller="SomeController">
    <input type="number" name="some-field" ng-model="numericValue" integer />
  </div>
</div>

<script>
  app = angular.module('myApp')

  app.directive('integer', function () {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, elm, attr, ctrl) {
        if (!ctrl) { return; }
        ctrl.$parsers.unshift(function (value) {
          return parseInt(value.replace(/\D/g, ''), 10);
        });
      }
    };
  });

  app.controller('SomeController' ['$scope', function ($scope) {});
</script>

app=angular.module('myApp')
app.directive('integer',function(){
返回{
要求:'ngModel',
限制:“A”,
链接:函数(作用域、elm、attr、ctrl){
如果(!ctrl){return;}
ctrl.$parsers.unshift(函数(值){
返回parseInt(value.replace(/\D/g'),10);
});
}
};
});
app.controller('SomeController'['$scope',function($scope){});
该指令将替换值中的任何非数字值,并在返回值之前通过
parseInt
方法运行它。问题是解析器方法的
value
参数始终为
null
,无论发生什么情况。不确定我是否使用了错误的函数,或者我的代码是否存在其他错误



编辑我在上创建了一个应用程序示例。尝试在字段中添加逗号之类的操作,看看输出结果如何。我发现问题的主要部分似乎是数字字段类型。当我使用文本字段类型时,它工作正常。

我的问题似乎与角度无关,而是与浏览器实现有关设置
输入[type=number]
。如果值不是数字,则在Chrome中
属性设置为
null


由于数字类型的实施,特别是Google Chrome的实施,我相信您将很难做到这一点。如果数字字段包含非数字值,它将被视为无效,内部值为“”。以防您真的得到它(例如,更改为使用type=“text”),不要忘记将格式化程序添加到
ctrl.$formatters
中,以确保双向绑定不会中断。