在AngularJS指令中将字符串转换为日期

问题描述 投票:1回答:2

我正在尝试转换字符串日期,以便它适用于类型设置为'date'的html输入。

所以,我有以下角度应用程序:

(function() {

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

    app.controller('MainCtrl', function($scope) {
        $scope.load = function() {                       
            $scope.message='2017-12-23T00:00:00Z';
        };
    });

    app.directive('convertDate', function() {
        return {
            restrict: 'A',
            scope: {
                ngModel: '='
            },
            link: function (scope) {    
                console.log(scope);
                console.log(scope.ngModel);

                if (scope.ngModel) scope.ngModel = new Date(scope.ngModel);
            }
        };            
    });
})();

然后我的HTML如下:

     <div ng-controller='MainCtrl'>         
        <input type="date" convert-date  ng-model="message">            
        <button ng-click="load()">load</button>
    </div>

当我点击加载按钮时,我收到以下错误:

错误:[ngModel:datefmt] http://errors.angularjs.org/1.6.4/ngModel/datefmt?p0=2017-12-23T00%3A00%3A00Z

我理解错误是因为它是一个字符串,我需要一个日期,这是我的指令的原因。

但即使有指令我仍然会得到错误。

我错过了什么?

谢谢

科林

angularjs angularjs-directive angularjs-ng-model
2个回答
1
投票

您可以将指令更改为以下内容:

 angular.module('app').directive('convertDate', function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {
        if (!ctrl) return;

        ctrl.$parsers.push(function(date) {
          if (angular.isDate(date))
            return new Date(date);
        })
      }
    }
  })

看看这个工作的plunker没有错误qazxsw poi


1
投票

这是因为您在ng-model中使用相同的变量进行转换。因此它会在您的指令转换之前遇到错误。

据我说,你应该先转换它,然后分配给控制器中的ng-model变量。

像这样,

https://plnkr.co/edit/8aSR1dlsRfDMrM7GfQQa?p=preview

无需使用指令

© www.soinside.com 2019 - 2024. All rights reserved.