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

时间:2014-07-16 20:00:18

标签: angularjs angularjs-directive

我正在尝试为修改模型的输入编写自定义指令,这样如果用户在输入中键入数字“25,000”,模型最终会以整数形式的值“25000”结束。 / p>

到目前为止我有这个代码:

<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>

该指令将替换值中的任何非数字值,并在返回值之前通过parseInt方法运行它。问题是解析器方法的value参数总是null,无论如何。不确定我是否使用了错误的功能,或者我的代码是否有其他问题。


修改我在jsFiddle上创建了我的应用示例。尝试在字段中添加逗号并查看输出结果。我发现问题的主要部分似乎是数字字段类型。当我使用文本字段类型时,它工作正常。

1 个答案:

答案 0 :(得分:0)

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

HTML5 input type=number value is empty in Webkit if has spaces or non-numeric characters?

相关问题