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 2122
借酒劲吻你
借酒劲吻你 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:10

    To use formatted date string instead of Date object as ng-model for Angular Datepicker, you need to create a wrapper directive. The wrapper directive will parse your string into Date object and pass it to the datepicker. When you select a date, it is converted from Date back into string. Here is an example (Plunker):

    (function () {
        'use strict';
    
        angular
            .module('myExample', ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
            .controller('MyController', MyController)
            .directive('myDatepicker', myDatepickerDirective);
    
        MyController.$inject = ['$scope'];
    
        function MyController ($scope) {
          $scope.dateFormat = 'dd MMMM yyyy';
          $scope.myDate = '30 Jun 2017';
        }
    
        myDatepickerDirective.$inject = ['uibDateParser', '$filter'];
    
        function myDatepickerDirective (uibDateParser, $filter) {
            return {
                restrict: 'E',
                scope: {
                    name: '@',
                    dateFormat: '@',
                    ngModel: '='
                },
                required: 'ngModel',
                link: function (scope) {
    
                    var isString = angular.isString(scope.ngModel) && scope.dateFormat;
    
                    if (isString) {
                        scope.internalModel = uibDateParser.parse(scope.ngModel, scope.dateFormat);
                    } else {
                        scope.internalModel = scope.ngModel;
                    }
    
                    scope.open = function (event) {
                        event.preventDefault();
                        event.stopPropagation();
                        scope.isOpen = true;
                    };
    
                    scope.change = function () {
                        if (isString) {
                            scope.ngModel = $filter('date')(scope.internalModel, scope.dateFormat);
                        } else {
                            scope.ngModel = scope.internalModel;
                        }
                    };
    
                },
                template: [
                    '
    ', '', '', '', '', '
    ' ].join('') } } })();
    
    
    
      
        
        
        
        
        
        
      
    
      
        

    Date format: {{dateFormat}}

    Value: {{myDate}}

提交回复
热议问题