2

I want to create a directive that will allow a user to input a date in a wide variety of formats. When the underlying model changes (whether via direct user input, or programmatically), I would like it to display the date in a normalized format.

An example of this "in the wild" are the departure and return date inputs on Google Flights.

Here's my code (which does not work at all).

VIEW

<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;
  }
});

DIRECTIVE

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;
            });
        }
    };
})

This doesn't even come close to working as I would expect. What am I doing wrong?

Here's a PLUNKR: http://plnkr.co/edit/583yOD6aRhRD8Y2bA5gU?p=preview

4

2 回答 2

3

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

我建议不要在您的指令中创建任何范围,并使用 attrs 访问 display-format 属性:

var displayFormat = attrs.displayFormat;
于 2013-08-01T16:18:55.223 回答
1

我也更喜欢带有可重用指令的隔离作用域,在这种情况下,必须为 ng-model 提供到父作用域的正确路径:ng-model="$parent.params.departDate"

更新的 plunker: http ://plnkr.co/edit/DuR6Om2kyzWD67hYExSh?p=preview

于 2014-01-09T12:49:44.843 回答