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 2151
借酒劲吻你
借酒劲吻你 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:20

    This is best solution i found so far:

    .directive('uibDatepickerPopup', 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 = uibDateParser.parse(value, dateFormat);
                        return !isNaN(date);
                    } else {
                        return false;
                    }
                };
            }
        };
    });
    

提交回复
热议问题