2016-05-16 63 views
0

任何人都可以解釋爲什麼Datepicker期望值是根據官方示例的日期對象? https://material.angularjs.org/latest/demo/datepickerAngular Material - Datepicker

說實話,這是一個痛苦,因爲服務器響應結合的形式之前,我必須確定一個字段的數據類型和轉換價值:

$scope.myDate = new Date('2015-01-11'); 

有什麼辦法我可以簡單地使用字符串值填充datepicker?

$scope.myDate = '2015-01-11'; 
+0

對不起,如果我的問題不清楚。我的意思是標準的HTML日期選擇器接受規範化的日期格式YYYY-MM-DD例如 '' 它非常容易綁定到它JSON/AJAX值直接來自服務器響應。 –

回答

0

字符串值的問題將被解析。 2016年5月10日和2016年10月5日可能會混淆。 2016-05-10或2016-10-05。日期對象可以防止這種情況發生。你不能使用已定義的過濾器將字符串數據轉換爲日期對象嗎?

我很快修改了一些日期過濾器中的代碼,我使用的是Angular 1.x,它使用YYYYMMDD(20160516)的數字日期格式。

/** 
* @name yourDate 
* @ngdoc filter 
* @requires $filter 
* @param DateValue {string} Date Value (YYYY-MM-DD) 
* @returns Date Filter with the Date Object 
* @description 
* Convert date from the format YYYY-MM-DD to the proper date object for future use by other objects/filters 
*/ 
angular.module('myApp').filter('yourDate', function($filter) { 
     var DateFilter = $filter('date'); 
     return function(DateValue) { 
      var Input = ""; 
      var ResultData = DateValue; 
      if (! ((DateValue === null) || (typeof DateValue == 'undefined'))) { 
       if (Input.length == 10) { 
        var Year = parseInt(Input.substr(0,4)); 
        var Month = parseInt(Input.substr(5,2)) - 1; 
        var Day = parseInt(Input.substr(8, 2)); 
        var DateObject = new Date(Year, Month, Day); 

        ResultData = DateFilter(DateObject);   // Return Input to the original filter (date) 
       } else { 
       } 
      } else { 
      } 
      return ResultData; 
     }; 
    } 
); 

/** 
* @description 
* Work with dates to convert from and to the YYYY-MM-DD format that is stored in the system. 
*/ 
angular.module('myApp').directive('yourDate', 
    function($filter) { 
     return { 
      restrict: 'A', 
      require: '^ngModel', 
      link: function($scope, element, attrs, ngModelControl) { 
       var slsDateFilter = $filter('yourDate'); 

       ngModelControl.$formatters.push(function(value) { 
        return slsDateFilter(value); 
       }); 

       ngModelControl.$parsers.push(function(value) { 
        var DateObject = new Date(value);     // Convert from Date to YYYY-MM-DD 
        return DateObject.getFullYear().toString() + '-' + DateObject.getMonth().toString() + '-' + DateObject.getDate().toString(); 
       }); 
      } 
     }; 
    } 
); 

此代碼僅使用標準的Angular Filter選項,因此您應該可以將其與Material date選取器結合使用。