Javascript 如何使用AngularJS ui date指令格式化初始日期值?

Javascript 如何使用AngularJS ui date指令格式化初始日期值?,javascript,angularjs,jquery-ui,angularjs-directive,angular-ui,Javascript,Angularjs,Jquery Ui,Angularjs Directive,Angular Ui,当我从服务器获取模型时,它如下所示: $scope.m = { name: "John", Dt: "2013-10-03T18:47:33.5049087-07:00" }; $http.get('data.json').success(function(data) { data.date = Date.parse(data.date); $scope.model = data; } 视图看起来像: <input title="Date" ui-da

当我从服务器获取模型时,它如下所示:

$scope.m = 
{
   name: "John",
   Dt:   "2013-10-03T18:47:33.5049087-07:00"
};
$http.get('data.json').success(function(data) {
    data.date = Date.parse(data.date);
    $scope.model = data;
}
视图看起来像:

<input title="Date" ui-date ng-model="m.Dt" />
但输入的初始值保持为“2013-10-03T18:47:33.5049087-07:00”。如果我使用日期选择器更改日期,它的格式仅为
mm dd yy


如何将初始值也设置为
mm-dd-yy
格式?

您的$scope.m.Dt属性应为日期类型,而不是字符串

$scope.m = 
{
   name: "John",
   Dt:   new Date()
};
要设置日期格式,请使用ui-date-format指令,如:

<input title="Date" ui-date ui-date-format="mm-dd-yy" ng-model="m.Dt" />

请参阅自述文件中的示例:

问题在于“日期”只是一个字符串,它需要一个本机日期对象(或时间戳)

我找到了两种处理方法:立即清除数据,或者观察变量并重新指定其类型

我的首选解决方案是在数据被引入时咀嚼数据。因为我知道对象有一个
日期
,所以我只需从
$http
成功
承诺中删除JSON数据,如下所示:

$scope.m = 
{
   name: "John",
   Dt:   "2013-10-03T18:47:33.5049087-07:00"
};
$http.get('data.json').success(function(data) {
    data.date = Date.parse(data.date);
    $scope.model = data;
}
在将数据分配给
$scope
之前对其进行转换,以便Angular将
$scope.model.date
视为本机JS日期对象,并正确格式化它

另一种解决方案是专门
$watch
变量的类型。在控制器的某个位置,添加以下内容:

$scope.$watch('model.date', function() {
    if (typeof $scope.model.date === 'string') {
        $scope.model.date = Date.parse($scope.model.date);
    }
});

每次修改
$scope.model.date
时检查类型。显然,这会增加开销,但在某些情况下可能会有用

我也有同样的问题。下面是我在Angularjs中使用Jquery UI日历所做的

日期格式为“2015-03-24T04:00:00”

首先修剪日期字符串以仅获取年、月和日期

var date = "2015-03-24T04:00:00"
var formattedDate = date.match(/[\d-]+/).pop();
// formattedDate is now "2015-03-24" which is passed into
// the directive below as the input.$modelValue.
现在,在指令或控制器中执行以下操作

// Here is directive example.
link: function( scope, element, attrs, input ){

  element.datepicker( optionsObjectHere );
  setInitialDateFormatOnInput();

  function setInitialDateFormatOnInput(){
    setTimeout(function(){ // This timeout is required to delay the directive for the input.modelValue to resolve, however, no actual delay occurs!
      element.datepicker( "setDate", formatToJqueryUIDateFormat());
    });
  }

  function formatToJqueryUIDateFormat(){
    return $.datepicker.parseDate( 'yy-mm-dd', input.$modelValue );
    // 'yy-mm-dd' needs to match the input.$modelValue format from above. 
  }
} // link
这就是我在输入上使用整个jquery UI的方式

HTML

指示

app.directive('myCalendarPopup', function(){

  var defaultOptions = { minDate: 0, buttonImage: "calendar-icon.png",   buttonImageOnly: 'true', showOn: "both", dateFormat: "MM d, yy" };
  // defaultOptions just in case someone doesn't pass in options.

  return {
    require:'?ngModel',
    restrict: 'A',

    link: function( scope, element, attrs, input ){
      if ( !input ){ return; } // If no ngModel then return;

      element.datepicker( createCalendarOptions());
      setInitialDateFormatOnInput();

      function createCalendarOptions(){
        if( !attrs.rsCalendarPopup ){ return addRequiredJqueryFunction( defaultOptions );}
        return formatOptions();
      }

      function formatOptions() {
        var options = scope.$eval( attrs.rsCalendarPopup );
        // Turn string into object above.
        return addRequiredJqueryFunction( options );
      }

      function addRequiredJqueryFunction( options ){
        options.onSelect = changeDate;
        // add onSelect to passed in object and reference local changeDate function, which will update changes to input.$modelValue.
        return options;
      }

      function changeDate( date ){
        input.$setViewValue( date );
      }

      function setInitialDateFormatOnInput(){
        setTimeout(function(){
        // This timeout is required to delay the directive for the input.modelValue to resolve.
        // However, there is no actual timeout time. This is a must to get
        // Angular to behave.
          element.datepicker( "setDate", formatToJqueryUIDateFormat());
        });
      }

      function formatToJqueryUIDateFormat(){
        return $.datepicker.parseDate( 'yy-mm-dd', input.$modelValue );
        // 'yy-mm-dd' is not the format you want the calendar to be
        // it is the format the original date shows up as.
        // you set your actual formatting using the calendar options at
        // the top of this directive or inside the passed in options.
        // The key is called dateFormat, in this case it's set as
        // dateFormat: "MM d, yy" which makes June 30, 2015.
      }
    } // link
  } // return
});
注意:我只能在它显示的配置中工作。我已将其添加到控制器,甚至是指令控制器,无法重新创建初始日期条件。我还不知道为什么会这样。也许这个解决方案只在嵌入到另一个独立的scope指令中的link函数中起作用,并且由于特定的定时而起作用


是的,我知道它适用于日期对象,但在一个真实的示例中,您的数据可能通过JSON来自服务器,并且您的日期将不是对象,而是字符串。我可以编写一个通过模型递归并将日期字符串转换为对象的方法,但我认为对于这样一个常见的场景,它已经被处理了。它不是以angular方式处理的,但您可以使用递归方法创建http拦截器,以将日期字符串转换为您提到的对象。例如,请参阅此帖子:
app.directive('myCalendarPopup', function(){

  var defaultOptions = { minDate: 0, buttonImage: "calendar-icon.png",   buttonImageOnly: 'true', showOn: "both", dateFormat: "MM d, yy" };
  // defaultOptions just in case someone doesn't pass in options.

  return {
    require:'?ngModel',
    restrict: 'A',

    link: function( scope, element, attrs, input ){
      if ( !input ){ return; } // If no ngModel then return;

      element.datepicker( createCalendarOptions());
      setInitialDateFormatOnInput();

      function createCalendarOptions(){
        if( !attrs.rsCalendarPopup ){ return addRequiredJqueryFunction( defaultOptions );}
        return formatOptions();
      }

      function formatOptions() {
        var options = scope.$eval( attrs.rsCalendarPopup );
        // Turn string into object above.
        return addRequiredJqueryFunction( options );
      }

      function addRequiredJqueryFunction( options ){
        options.onSelect = changeDate;
        // add onSelect to passed in object and reference local changeDate function, which will update changes to input.$modelValue.
        return options;
      }

      function changeDate( date ){
        input.$setViewValue( date );
      }

      function setInitialDateFormatOnInput(){
        setTimeout(function(){
        // This timeout is required to delay the directive for the input.modelValue to resolve.
        // However, there is no actual timeout time. This is a must to get
        // Angular to behave.
          element.datepicker( "setDate", formatToJqueryUIDateFormat());
        });
      }

      function formatToJqueryUIDateFormat(){
        return $.datepicker.parseDate( 'yy-mm-dd', input.$modelValue );
        // 'yy-mm-dd' is not the format you want the calendar to be
        // it is the format the original date shows up as.
        // you set your actual formatting using the calendar options at
        // the top of this directive or inside the passed in options.
        // The key is called dateFormat, in this case it's set as
        // dateFormat: "MM d, yy" which makes June 30, 2015.
      }
    } // link
  } // return
});