AJAX转换日期javascript日期与NG-模型使用日期、模型、AJAX、NG

2023-09-13 05:06:51 作者:渣渣中渣渣

我在服务中使用$ http.get获取JSON数据。一个在返回的JSON我的对象属性的是这是不被AngularJS解析的日期。我需要这个属性绑定到一个日期字段,我目前围绕它致力于通过如下所示

I am using $http.get in a service in to fetch JSON data. One of my object properties in the returned JSON is a date which is not being parsed by AngularJS. I need to bind this property to a date field and I am currently working around it by manually converting the JSON string to a javascript date after fetching the AJAX data as shown below

app.service('MainService', function(){
  var self = this;
  self.jsonDate = null;
  self.parsedDate = null;

  // this function will get JSON data from an API in production
  self.getData = function(){
    var jsonData = "2014-06-13T16:00:00";

    // Angular does not convert my JSON data properties into dates
    self.jsonDate = jsonData;

    // I can work around this by forcing my dates to be parsed
    self.parsedDate = moment(jsonData).toDate();
  }
});

是否有这样做的更清洁的方式?我建了一个过滤器,一个字符串转换为日期

Is there a cleaner way of doing this? I built a filter that converts a string to a date

app.filter('stringToDate', function () {
    return function (input) {
        if (!input)
            return null;

        var date = moment(input);
        return date.isValid() ? date.toDate() : null;
    };
});

该过滤器的伟大工程,如果我用它如下所示

The filter works great if I use it as shown below

<span ng-bind="service.jsonDate | stringToDate | date:'MM/dd/yy'"></span>

但如果我尝试用NG-模型使用如下图所示。

but it does not work if I try to use it with ng-model as shown below

<input type="date" ng-model="service.jsonDate | stringToDate"/>

可以过滤与NG-模型中使用或是否需要坚持使用性质手动转换为日期?我这里有一个plunker演示我目前的code

Can a filter be used with ng-model or do I need to stick with manually converting properties to dates? I have a plunker here that demonstrates my current code

http://plnkr.co/edit/pVaDbjIjtnKaYqrjAd0D?p=$p$ PVIEW

推荐答案

Plunker演示这里

有几个方法,你可以这样做:

There are few ways you can do this:

使用在NG-INIT过滤器初始化范围变量,则NG-模式绑定到范围变量。

Use the filter in ng-init to initialize a scope variable, then bind the ng-model to the scope variable.

<body ng-controller="MainCtrl" ng-init="mydate = (service.jsonDate | stringToDate)">
    <label>Raw JSON Date</label>
    <input type="date" data-ng-model="service.jsonDate"/><br/><br/>

    <label>Parsed JSON date</label>
    <input type="date" data-ng-model="mydate"/>
 </body>

使用 $过滤器服务手动调用你的控制器中的 stringToDate 过滤器:

入门JavaScript之前,你需要知道JavaScript的前世今生

Use the $filter service to manually invoke the stringToDate filter in your controller:

app.controller('MainCtrl', function($scope, $filter, MainService) {
    $scope.service = MainService;

    // fetch data from service
    $scope.service.getData();

    $scope.parsedDate = $filter('stringToDate')(MainService.jsonDate);

});

和则变量绑定到你的 NG-模型

<input type="date" data-ng-model="parsedDate"/>

使用依赖于一个NG-模型,是生JSON一个定制指令 。添加格式化到模型的日期字符串转换;和解析器日期字符串转换回模型。这种方法的优点是,该模型结合双向保持。当您更新使用有效的日期字符串文本框,它会自动更新的原始JSON模式(反之亦然)。

Use a custom directive which relies on an ng-model that is raw JSON. Add a formatter to convert the model to a date string; and a parser to convert the date string back to the model. The advantage of this approach is that the two-way model binding is maintained. When you update the text box with a valid date string, it automatically updates the raw JSON model (and vice versa).

在plunker例如,尝试输入一个有效的日期字符串,并注意模型自动更改。

In the plunker example, try entering a valid date string, and notice how the model automatically changes.

指令:

   app.directive('jsonDate', function($filter) {
      return  {
          restrict: 'A',
          require: 'ngModel',
          link: function (scope, element, attrs, ngModel) {

             //format text going to user (model to view)
             ngModel.$formatters.push(function(value) {
                var date = $filter('stringToDate')(value);
                return date.toString();
             });

             //format text from the user (view to model)
             ngModel.$parsers.push(function(value) {
                var date = new Date(value);
                if (!isNaN( date.getTime())) { 
                   return moment(date).format();
                }
             });
         }
     }

HTML:

 <input type="date" data-ng-model="service.jsonDate" json-date/>

这最后一个例子可以让你的ngModel绑定到一个JSON日期字符串,并将它显示一个格式化的日期。当用户输入一个有效的格式化的日期,它会自动更新JSON日期字符串模式,它绑定到

This last example allows you to bind an ngModel to a json date string and have it display a formatted date. When the user enters a valid formatted date, it automatically updates the json date string model that its bound to