angularjs - 无法弄清楚如何使用 $parsers 和 $formatters 创建指令

标签 angularjs angularjs-directive

我想创建一个指令,允许用户输入多种格式的日期。当底层模型发生变化时(无论是通过直接用户输入还是以编程方式),我希望它以标准化格式显示日期。

这种“野外”的一个例子是 Google Flights 上的出发和返回日期输入。 .

这是我的代码(根本不起作用)。

查看

<input type="text" ng-model="params.departDate" 
  date-input display-format="{Weekday} {d} {Month}, {yyyy}">

Controller

app.controller('MainCtrl', function($scope) {
  $scope.params = {
      departDate: new Date()
  };
  $scope.isDate = function() {
      return $scope.params.departDate instanceof Date;
  }
});

指令

app.directive("dateInput", function() {
    return {
        require: 'ngModel',
        scope: {
            displayFormat: '@'
        },
        link: function (scope, element, attrs, ngModel) {

            ngModel.$parsers.push(function (viewVal) {
                if (viewVal) {
                    // Using sugar.js for date parsing
                    var parsedValue = Date.create(viewVal);
                    if (parsedValue.isValid()) {
                        ngModel.$setValidity("date", true);
                        return parsedValue;
                    }
                }
                ngModel.$setValidity("date", false);
                return viewVal;
            });

            ngModel.$formatters.unshift(function (modelVal) {
                if (modelVal){
                    // Using sugar.js for date formatting
                    var date = Date.create(modelVal);
                    if (date.isValid()) {
                        return date.format(scope.displayFormat || '{Weekday} {d} {Month}, {yyyy}')
                    }
                }
                return modelVal;
            });
        }
    };
})

这甚至没有达到我预期的效果。我做错了什么?

这是一个 PLUNKR:http://plnkr.co/edit/583yOD6aRhRD8Y2bA5gU?p=preview

最佳答案

正如评论中提到的,ng-model 和隔离范围不能很好地混合,请参阅 Can I use ng-model with isolated scope? .

我建议不要在指令中创建任何范围,并使用 attrs 访问显示格式属性:

var displayFormat = attrs.displayFormat;

关于angularjs - 无法弄清楚如何使用 $parsers 和 $formatters 创建指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17997535/

相关文章:

javascript - 当尝试覆盖 $exceptionHandler 时,简单的 javascript 异常在 Angular Controller init 上发生 7 次

javascript - 一个 Controller 的值应该可供其他 Controller 使用

javascript - 如何在 Angular JS 中输入小时和分钟?

javascript - 正则表达式使链接可点击(仅在 'a href' 而不是 'img src' )

javascript - 访问使用类的 ngModel 元素

javascript - 在 ng-repeat 中使用指令,以及范围 '@' 的神秘力量

javascript - Angular Directive(指令) : Is there a better way than '$timeout' to get info about DOM elements created in "compile" function?

angularjs - 在 Angular 中断验证中打破多个选项卡之间的表单

javascript - Angular : Modify model of parent scope in a directive with '=xxx' isolate scope?

angularjs - 如何在指令模板中使用范围