Angular.js and HTML5 date input value — how to get Firefox to show a readable date value in a date input?

前端 未结 7 1978
無奈伤痛
無奈伤痛 2020-12-12 13:26

I have an HTML5 date input and I would like its value to be set to the value of the date property in my model by default. I\'m not too fussy about formatting since Chrome se

7条回答
  •  有刺的猬
    2020-12-12 14:19

    The problem is that value is ignored when ng-model is present.

    Firefox, which doesn't currently support type="date", will convert all the values to string. Since you (rightly) want date to be a real Date object and not a string, I think the best choice is to create another variable, for instance dateString, and then link the two variables:

    
    
    function MainCtrl($scope, dateFilter) {
        $scope.date = new Date();
    
        $scope.$watch('date', function (date)
        {
            $scope.dateString = dateFilter(date, 'yyyy-MM-dd');
        });
    
        $scope.$watch('dateString', function (dateString)
        {
            $scope.date = new Date(dateString);
        });
    }
    

    Fiddle

    The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:

    • allow formats other than yyyy-MM-dd,
    • be able to use NgModelController#$formatters and NgModelController#$parsers rather than the artifical dateString variable (see the documentation on this subject).

    Please notice that I've used yyyy-MM-dd, because it's a format directly supported by the JavaScript Date object. In case you want to use another one, you must make the conversion yourself.


    EDIT

    Here is a way to make a clean directive:

    myModule.directive(
        'dateInput',
        function(dateFilter) {
            return {
                require: 'ngModel',
                template: '',
                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);
                    });
                },
            };
    });
    

    Fiddle

    That's a basic directive, there's still a lot of room for improvement, for example:

    • allow the use of a custom format instead of yyyy-MM-dd,
    • check that the date typed by the user is correct.

提交回复
热议问题