6

给定一个返回 json 值的 WebApi2 服务,如下所示:

{
    id: 1109,
    effectiveDate: "2014-10-05T00:00:00", // the date is a string (newtonsoft.json)
    text: "Duis et rhoncus nibh. Cras rhoncus cursus diam",
    fundSource: "Test"
}

我需要日期正确出现在绑定的角度/引导程序/日期选择器中。

在将日期绑定到输入框时,我需要将日期转换为 yyyy-mm-dd 格式(没有时间)。只是指向一些文档的指针,该文档解释了将日期从 API 序列化为角度的正确方法。我确信它effectiveDate实际上应该是一个Date对象而不是一个string.

<input class="form-control" 
       type="text" 
       name="effectiveDate" 
       ng-model="consultation.effectiveDate" 
       data-date-picker="yyyy-mm-dd" 
       placeholder="Date" />

为了完整起见,返回 json 值的服务如下所示:

app.factory('Service', ['$http', '$location', '$interpolate', function ($http, $location, $interpolate) {
    return {
        get: function (account) {
            var url = 'api/consultations/{account}';
            return $http
                .get(Api.format(url, { account: account }))
                .then(function (response) { return response.data; });
        }
    };
}]);

控制器方法这样调用它:

service.get($scope.urlData.account).then(function(consultations) {
    $scope.consultations = consultations;
});
4

3 回答 3

3

我遇到了完全相同的问题,并最终通过编写 Angular 解决了它http interceptor。它解析服务器的响应并将所有具有 ISO/UTC 格式的 Datetime 字符串转换为实际的 JavaScript 日期对象。这允许直接绑定到日期选择器并解决验证问题。

这是客户端 Angular 代码,由工厂(拦截器)和用于提供 http 拦截器的配置部分组成:

angular.module("app")
    .factory('dateInterceptor', function () {
        var regexIsoUtc = /^(\d{4}|\+\d{6})(?:-(\d{2}))(?:-(\d{2}))(?:T(\d{2})):(\d{2}):(\d{2})Z$/;

        function matchDate(dateString) {
            if (dateString.length === 20) {
                return dateString.match(regexIsoUtc);
            }
            return false;
        };

        function convertDateStringsToDates(object) {
            // ensure that we're processing an object
            if (typeof object !== "object") {
                return object;
            }

            for (var key in object) {
                if (!object.hasOwnProperty(key)) {
                    continue;
                }
                var value = object[key];

                // check for string properties with a date format
                if (typeof value === "string" && matchDate(value)) {
                    var date = new Date(value); // create the date from the date string
                    object[key] = date; // we're mutating the response directly
                } else if (typeof value === "object") {
                    convertDateStringsToDates(value); // recurse into object
                }
            }
            return null;
        }

        var interceptor = {
            'response': function (response) {
                if (response.data) {
                    convertDateStringsToDates(response.data);
                }
                return response;
            }
        };
        return interceptor;
    })

    .config(["$httpProvider", function ($httpProvider) {
        $httpProvider.interceptors.push('dateInterceptor'); // intercept responses and convert date strings into real dates
    }]);

在服务器端,我配置为使用带有UTC time zone的ISO 格式Newtonsoft.Json序列化日期,这是我在拦截器中测试的格式:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var formatters = GlobalConfiguration.Configuration.Formatters;
        var jsonFormatter = formatters.JsonFormatter;
        var settings = jsonFormatter.SerializerSettings;

        // serialize dates into ISO format with UTC timezone
        settings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
        settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
}

幸运的是,拦截器基于Automatic JSON date parsing with AngularJSAngularJS HTTP Date Interceptor Factory中的代码。

于 2015-10-30T18:15:44.350 回答
2

在angularjs中使用角度过滤器模块日期过滤器

{{ effectiveDate | date:'yyyy-MM-dd' }}
于 2014-10-08T05:55:37.977 回答
1

如果你想在 Angular 中使用引导组件,那么你必须创建一个指令,或者你可以重用一些现有的,比如http://angular-ui.github.io/bootstrap/#/datepicker

示例如何使用带角度的引导日期选择器:

 <body ng-app="app" >

    <div class="form-horizontal" ng-controller="ctrl">
        <input type="text" datepicker-popup="MM/dd/yyyy" ng-model="consultation.effectiveDate" datepicker-options="dateOptions" date-disabled="" ng-required="true" />
    </div>
 </body>

js:

app.controller('ctrl', function ($scope, $timeout) {

 $scope.consultation = {
    id: 1109,
    effectiveDate: "2014-10-05T00:00:00", // the date is a string (newtonsoft.json)
    text: "Duis et rhoncus nibh. Cras rhoncus cursus diam",
    fundSource: "Test"
  };

  $scope.dateOptions = {
    'starting-day': 1
  };
});

http://plnkr.co/edit/veOWWlBrKdL5CaMJf61h?p=preview

于 2014-10-08T05:52:54.160 回答