Sun
Sun

Reputation: 4718

Convert string to date in AngularJS directive

I'm trying to convert a string date so that it works on a html input with the type set to 'date'.

So, I have the following angular app:

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

Then my html is as follows:

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

When I click on the load button I get the following error:

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

I understand the error is because it's a string and I need a date, which its the reason for my directive.

But even with the directive I still get the error.

What am I missing?

Thanks

Colin

Upvotes: 1

Views: 3442

Answers (2)

Rathma
Rathma

Reputation: 1313

You can change your directive to following:

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

take a look at this working plunkr without error https://plnkr.co/edit/8aSR1dlsRfDMrM7GfQQa?p=preview

Upvotes: 1

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

It is because you are using same variable in ng-model for converting. So it encounters an error before your directive converts it.

According to me, you should convert it first and then assign to the ng-model variable in your controller.

Like this,

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

})();

No need to use directive

Upvotes: 1

Related Questions