date-input ng

by manoj

HTML

<body ng-app="MyApp">    
    <div ng-controller="MainCtrl">
        <input date-input ng-model="date" />
        <br/>{{ date }}
        <br/>{{ date | date: 'yyyy-MM-dd' }}
    </div>
</body>

JavaScript

angular
    .module('MyApp', [])
    .controller('MainCtrl', function ($scope, dateFilter) {
        $scope.date = new Date();
    })
    .directive(
        'dateInput',
        function(dateFilter) {
            return {
                require: 'ngModel',
                template: '<input type="date"></input>',
                replace: true,
                link: function(scope, elm, attrs, ngModelCtrl) {
                    ngModelCtrl.$formatters.unshift(function (modelValue) {
                        return dateFilter(modelValue, 'yyyy-MM-dd');
                    });
                    
                    ngModelCtrl.$parsers.unshift(function(viewValue) {
                        return new Date(viewValue);
                    });
                },
            };
    });