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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19170501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:39:11  来源:igfitidea点击:

How to format inital date value using AngularJS ui-date directive?

javascriptangularjsjquery-uiangularjs-directiveangular-ui

提问by CHS

When I get a model from the server it looks like this:

当我从服务器获取模型时,它看起来像这样:

$scope.m = 
{
   name: "John",
   Dt:   "2013-10-03T18:47:33.5049087-07:00"
};

The view looks like:

视图看起来像:

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

I set the default date format on the jQuery datepicker to:

我将 jQuery datepicker 上的默认日期格式设置为:

$.datepicker.setDefaults({dateFormat: 'mm-dd-yy'});

The initial value of the input stays "2013-10-03T18:47:33.5049087-07:00" though. It only formats as mm-dd-yyif I use the datepicker to change the date.

但是输入的初始值保持为“2013-10-03T18:47:33.5049087-07:00”。它的格式就像mm-dd-yy我使用日期选择器来更改日期一样。

How can I get the initial value to also be in mm-dd-yyformat?

如何使初始值也采用mm-dd-yy格式?

采纳答案by Alexander Puchkov

Your $scope.m.Dt property should be of date type, not string.

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

$scope.m = 
{
   name: "John",
   Dt:   new Date()
};

To set date format use ui-date-formatdirective, like:

要设置日期格式,请使用ui-date-format指令,例如:

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

See example in readme: https://github.com/angular-ui/ui-date#ui-date-format-directive

请参阅自述文件中的示例:https: //github.com/angular-ui/ui-date#ui-date-format-directive

回答by joemaller

The problem is that the "date" is just a string, Angular wants a native Date object (or a timestamp).

问题是“日期”只是一个字符串,Angular 想要一个原生的 Date 对象(或时间戳)。

I've found two ways of dealing with this: Scrub the data right away or watch the variable and reassign its type.

我找到了两种处理方法:立即清理数据或观察变量并重新分配其类型。

My preferred solution is to munge the data when it's brought in. Since I know the object has a date, I just scrub the JSON data from the $httpsuccesspromise like this:

我的首选解决方案是在数据被引入时对其进行处理。因为我知道该对象有一个date,所以我只是$httpsuccess像这样从promise 中清除 JSON 数据:

$http.get('data.json').success(function(data) {
    data.date = Date.parse(data.date);
    $scope.model = data;
}

That converts the data before it's assigned to $scope, so Angular will see $scope.model.dateas a native JS Date object format it correctly.

这会在将数据分配给 之前转换数据$scope,因此 Angular 会将其$scope.model.date视为本机 JS 日期对象格式正确。

The other solution is to specifically $watchthe variable's type. Somewhere in the controller, add this:

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

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

That checks the type everytime $scope.model.dateis modified. Obviously, that's more overhead, but might be useful in some cases.

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

回答by SoEzPz

I had the same issue. Here is what I did using Jquery-UI calendar with Angularjs

我遇到过同样的问题。这是我在 Angularjs 中使用 Jquery-UI 日历所做的

date format was "2015-03-24T04:00:00"

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

First trim the date string to get only year, month, and date.

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

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.

Now, inside your directive or controller do the following...

现在,在您的指令或控制器中执行以下操作...

// 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

This is how I use the entire jquery UI on my inputs.

这就是我在输入中使用整个 jquery UI 的方式。

HTML

HTML

<input type="text" class="inline" ng-model="inputValue" my-calendar-popup="calendarOptions" />

Where calendarOptions is the following object

其中 calendarOptions 是以下对象

  var calendarOptions = { minDate: 0, buttonImage: "calendar-icon.png", buttonImageOnly: 'true', showOn: "both", dateFormat: "MM d, yy" };

DIRECTIVE

指示

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
});

Note: I can only get this to work in it's displayed configuration. I have added it to a controller, and even a directive controller and could not recreate the initial date condition. I have not found out why this is yet. Perhaps this solution works only within a link function that is embedded in another isolated scope directive and works due to specific timing.

注意:我只能让它在显示的配置中工作。我已将它添加到控制器,甚至是指令控制器,但无法重新创建初始日期条件。我还没有发现为什么会这样。也许此解决方案仅适用于嵌入在另一个隔离范围指令中的链接函数,并且由于特定时间而起作用。