【问题标题】:angular: How to change the data type using $formatters and $parsers?angular: 如何使用 $formatters 和 $parsers 更改数据类型?
【发布时间】:2014-09-04 05:47:48
【问题描述】:

使用 ngModel.$formatters 和 ngModel.$parsers 我正在尝试创建一个指令来将数据类型从模型更改为视图,反之亦然。

问题是当我使用<input type="number"> 在这种情况下,toView 接收“未定义”作为值,但不接收字符串数据。 ("1234")

如果我删除 type=number 可以正常工作,但输入元素不是我想要的。

有什么方法可以让它工作吗?

如果没有,还有其他方法可以达到这个目的吗? (模型必须是字符串,输入必须是 type="number")

PLUNK

javascript

var app = angular.module('module', []);

app.controller('MainCtrl', function($scope) {
  $scope.model = {};
  $scope.model.number = "1234";
});

app.directive('numberConverter', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: {
      pre: function(scope, element, attr, ngModel) {

        function toModel(value) {
          return "" + value; // convert to string
        }

        function toView(value) {
          return parseInt(value); // convert to number
        }

        ngModel.$formatters.unshift(toView);
        ngModel.$parsers.unshift(toModel);
      },
      post: function() {}
    }
  };
});

html

<input type="number" number-converter ng-model="model.number">

【问题讨论】:

    标签: angularjs angularjs-directive type-conversion


    【解决方案1】:

    对不起,我原来的答案不太正确。

    这是一个更新的指令,它将正确地将值存储为字符串,但将其编辑为数字。

    指令的优先级大于 0(默认优先级)非常重要,这样它才能在 ngModel 指令之后运行。这可以确保您在默认值之后添加格式化程序和解析器(否则您只是推送到一个空列表,并且默认处理器将在您的之后添加)。

    app.directive('numberConverter', function() {
        return {
            restrict: 'A',
            require: 'ngModel',
            priority: 1,
            link: function(scope, element, attr, ngModel) {
    
                function toModel(value) {
                    return "" + value; // convert to string
                }
    
                function toView(value) {
                    return parseInt(value); // convert to number
                }
    
                ngModel.$formatters.push(toView);
                ngModel.$parsers.push(toModel);
            }
        };
    });
    

    更新 plunkr:http://plnkr.co/edit/l8c1GGBeIX4dawLZJfoC?p=preview

    【讨论】:

    • {link: function(){}}{link: {postLink: function(){}}} 的简写——它们是一样的。
    • +1,我冒昧地分叉了 plnkr 并为 type 添加了模型字段,以便更容易地证明它的工作原理:plnkr.co/edit/uCLmwZhjwlPtmXnj5Hw3?p=preview
    猜你喜欢
    • 2017-07-28
    • 1970-01-01
    • 2017-08-24
    • 2017-05-06
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多