代码之家  ›  专栏  ›  技术社区  ›  Sun

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

  •  1
  • Sun  · 技术社区  · 7 年前

    我正在尝试转换字符串日期,以便它在类型设置为“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

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

    但即使有了指令,我仍然会出错。

    我错过了什么?

    谢谢

    科林

    2 回复  |  直到 7 年前
        1
  •  1
  •   Rathma    7 年前

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

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

    请仔细查看此正在工作的plunkr,无误 https://plnkr.co/edit/8aSR1dlsRfDMrM7GfQQa?p=preview

        2
  •  1
  •   Shridhar Sharma    7 年前

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

    根据我的说法,您应该首先转换它,然后将其分配给控制器中的ng模型变量。

    这样地,

    (function() {
    
        var app = angular.module('test', []);
    
        app.controller('MainCtrl', function($scope) {
            $scope.load = function() {
                var dateString = '2017-12-23T00:00:00Z';
                $scope.message=new Date(dateString);
            };
        });
    
    })();
    

    无需使用指令