2014-10-08 54 views
6

鑑於返回這樣JSON值的WebApi2服務:結合使用的WebAPI angularjs日期和自舉日期選擇器

{ 
    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" 
} 

我需要的時間出現在結合的角/引導/ date picker正確。

我需要將日期轉換爲格式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" /> 

對於completness,返回的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; 
}); 
+0

將字符串格式的日期轉換爲JavaScript Date對象。其餘的應該可以正常工作。您可以在JavaScript中使用普通JavaScript進行日期時間處理,但最好使用一些處理跨瀏覽器兼容性的庫。你可以試試moment.js。您的範圍變量effectiveDate應該包含Date對象。 – 2014-10-08 04:36:07

回答

1

如果你想使用引導組件角度,那麼你必須創建一個指令,或者你可以重用一些現有的像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

3

我跑進確切同樣的問題,並最終通過編寫一個解決方案n角形http interceptor。 它解析服務器的響應並將所有日期時間字符串轉換爲實際的JavaScript日期對象。 這允許直接綁定到日期選擇器並解決驗證問題。

這裏的客戶機側角代碼,由工廠(攔截)和配置部分用於提供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 
    }]); 

在服務器端我配置Newtonsoft.Json序列化日期使用ISO格式UTC時區,這是我在攔截器中測試的格式:

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的代碼。

相關問題