【问题标题】:Angular directive with ngModelController formatter带有 ngModelController 格式化程序的 Angular 指令
【发布时间】:2014-08-15 07:20:51
【问题描述】:

我正在尝试实现一个简单的指令,将格式化程序添加到<input type="date"> 字段。该指令如下所示:

myApp.directive("date-format", function (dateFilter) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attributes, ngModelController) {
            ngModelController.$formatters.push(function (modelValue) {
                return modelValue && new Date(modelValue);
            });
        }
    };
});

在我将其名称更改为 mb-date-format 之前,它运行良好。我创建了一个 JS 小提琴:http://jsfiddle.net/HB7LU/4458/。它似乎可以与 aaabbbccc 等名称一起正常工作,但是当您将名称更改为 jjjzzz、...时,它就会停止工作。

【问题讨论】:

  • 尝试优先考虑你的指令;我不记得某些机制,但让它在input 指令之前或之后显式运行(例如priority: 10priority: -10)。当多个指令具有相同的优先级(例如默认)时,Angular 似乎按字母顺序排列它们。
  • 它绝对适用于例如priority: 1,似乎 0 是默认优先级,input 指令也具有 0 优先级。谢谢!

标签: angularjs angularjs-directive angular-ngmodel


【解决方案1】:

尝试将指令名称以驼峰形式转换为“dateFormat”,例如:

myApp.directive("dateFormat", function (dateFilter) 


然后在像这样的html中使用它

<input type="date" ng-model="date" date-format>

【讨论】:

    【解决方案2】:

    查看您的小提琴,我发现了几个可能是原因的问题:

    1. 您在输入中使用date 类型。内置的浏览器日期选择器 API 很难覆盖,因此您的格式化解决方案在许多浏览器中都不起作用。

    解决方案一: 将输入类型更改为文本

    &lt;input type="text" ng-model="date" mb-date-format&gt;

    我了解这意味着您可能必须滚动自己的选择器,但如果您想要自定义,则需要这样做。如果你不介意依赖,并且你的要求不是太多,AngularUI makes a pretty extensible datepicker

    1. 您的解析器函数永远不会受到影响,而且您可能不需要解析器来进行格式化。

    解决方案第二部分: 在格式化程序函数I modified your fiddle here 中格式化输出,这也实现了您最初查询的指令名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 2019-11-19
      • 1970-01-01
      相关资源
      最近更新 更多