格式化 ng-model 的初始值(使用 datePicker 输入类型文本)

Format the initial value of the ng-model (input type text with datePicker)

我有一个带日期选择器的输入类型文本。

<input id="start-date" style="width: 230px;" close-text="Close"
 type="text" ng-model="startDate"  datepicker-popup="dd-MM-yyyy"  
ng-required="true"/></div>

显示输入时,我必须为其显示一个初始值。问题是这个值以这种格式显示:

Wed Jun 15 2016 10:48:49 GMT+0000 (WET)

从日期选择器中选择一个日期后,我就可以看到我想要的格式 (dd-MM-yyyy)。为了解决这个问题,我添加了:

$scope.$watch('startDate', function (newValue) {
  $scope.startDate = $filter('date')(newValue, 'dd-MM-yyyy');
});

但我收到此错误:Datepicker 指令:"ng-model" 值必须是 Date 对象,自 01.01.1970 以来的毫秒数或表示 RFC2822 或 ISO 8601 日期的字符串。

我该如何解决这个问题?

谢谢!

假设您使用的是 AngularUI 日期选择器并且您的 ng-Model 初始值未格式化,只需将以下指令添加到您的项目即可解决问题:

directive('datepickerPopup', function (){
  return {
    restrict: 'EAC',
    require: 'ngModel',
    link: function(scope, element, attr, controller) {
      //remove the default formatter from the input directive to prevent conflict
      controller.$formatters.shift();
    }
  }
})