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 2117
借酒劲吻你
借酒劲吻你 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

    I had the same problem. The issue is that Angular is expecting an actual date object, not a string representation of the date. After doing a bunch of research I ended up adding a transformReponse to the $httpProvider which checks all string objects to see if they can be converted to a date, and if so actually converting them.

    angular.module('test')
    .config(['$httpProvider', function ($httpProvider) {
    
        // ISO 8601 Date Pattern: YYYY-mm-ddThh:MM:ss
        var dateMatchPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
    
       var convertDates = function (obj) {
          for (var key in obj) {
             if (!obj.hasOwnProperty(key)) continue;
    
             var value = obj[key];
             var typeofValue = typeof (value);
    
             if (typeofValue === 'object') {
                // If it is an object, check within the object for dates.
                convertDates(value);
             } else if (typeofValue === 'string') {
                if (dateMatchPattern.test(value)) {
                   obj[key] = new Date(value);
                }
             }
          }
       }
    
       $httpProvider.defaults.transformResponse.push(function (data) {
          if (typeof (data) === 'object') {
             convertDates(data);
          }
    
          return data;
       });
    }])
    

提交回复
热议问题