0

I need to capture date data in dd/MM/yyyy format and need to send it to the API as Date object. I am using the following directive:

angular.module('tmyapp').directive('formattedDate', function (dateFilter) {
    return {
        require: 'ngModel',
        scope: {
            format: "="
        },
        link: function (scope, element, attrs, ngModelController) {
            ngModelController.$parsers.push(function (data) {
                //convert data from view format to model format
                return dateFilter(data, scope.format); //converted
            });

            ngModelController.$formatters.push(function (data) {
                //convert data from model format to view format
                return dateFilter(data, scope.format); //converted
            });
        }
    }
});
//use <input type="text" formatted-date format="'dd/MM/yyyy'" />

It is working in showing the Date Object to dd/MM/yyyy but fails to convert the data in dd/MM/yyyy format to Date object.

Can someone help?

2
  • Parser shouldn't parse the date to return a Date object? Commented Jul 9, 2016 at 21:29
  • Right, but simply passing the data in string dd/MM/yyyy format to the date method doesn't work. I am looking for a way to do this. Commented Jul 10, 2016 at 5:34

1 Answer 1

1

You have to parse date String in parser like this:

angular.module('tmyapp').directive('formattedDate', function (dateFilter) {
    return {
        require: 'ngModel',
        scope: {
            format: "="
        },
        link: function (scope, element, attrs, ngModelController) {
            ngModelController.$parsers.push(function (data) {
                //convert data from view format to model format
                dateArray = data.split("/");
                var date = new Date(dateArray[2] + "-" + dateArray[1] + "-" + dateArray[0])
                return date; //converted
            });

            ngModelController.$formatters.push(function (data) {
                //convert data from model format to view format
                return dateFilter(data, scope.format); //converted
            });
        }
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

So, this will make the directive work for this particular format only. And if I need to use other formats, I might have to add additional parsers. Is that right?
You can make it as conditional as you like based on the format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.