Angular-UI date picker is in invalid state when specified the date format as 'd-M-yyyy' and ng-model with a string value as “2014-08-31T00:00:00Z”

后端 未结 7 2118
借酒劲吻你
借酒劲吻你 2021-02-15 23:49

I am getting a date time value from asp.net mvc controller as \"2014-08-31T00:00:00Z\". When I bind this value to my angular-ui datepicker control it\'s state is showing as ng-i

7条回答
  •  野的像风
    2021-02-16 00:04

    Just wanted to add my solution to this stack.

    app.directive('formatDate', function (dateFilter, uibDateParser, uibDatepickerPopupConfig) {
        return {
            restrict: 'A',
            priority: 1,
            require: 'ngModel',
            link: function (scope, element, attr, ngModel) {
                var dateFormat = attr.uibDatepickerPopup || uibDatepickerPopupConfig.datepickerPopup;
                ngModel.$validators.date = function(modelValue, viewValue) {
                    var value = viewValue || modelValue;
    
                    if (!attr.ngRequired && !value) {
                        return true;
                    }
    
                    if (angular.isNumber(value)) {
                        value = new Date(value);
                    }
                    if (!value) {
                        return true;
                    } else if (angular.isDate(value) && !isNaN(value)) {
                        return true;
                    } else if (angular.isString(value)) {
                        var date = new Date(value);
                        return !isNaN(date);
                    } else {
                        return false;
                    }
                }
                ngModel.$formatters.push(function(value) {
                    return new Date(value);
                });
            }
        };
    });
    

提交回复
热议问题