2014-10-08 12 views
6

Biorąc usługę WebApi2 która zwraca wartości json tak:wiążąca data w angularjs wykorzystujących WebAPI oraz datę bootstrap kompletacji

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

muszę datę pojawiać się w związanej kątowej/bootstrap/date picker poprawnie .

Muszę przekształcić datę na format yyyy-mm-dd (bez czasu), kiedy wiążę ją z polem wprowadzania danych. Tylko wskaźnik do niektórych dokumentów wyjaśniających, jaki jest poprawny sposób serializowania dat z API na kątowy. Jestem pewien, że effectiveDate powinien być obiektem Date, a nie string.

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

Dla kompletności, usługa zwrotu wartości json wygląda następująco:

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

Metoda kontroler nazywa to tak:

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

Konwertuj datę w formacie ciągu na obiekt Date JavaScript. Reszta powinna działać dobrze. Możesz używać normalnego JavaScript do obsługi Date-Time w JavaScript, ale lepiej użyć biblioteki obsługującej kompatybilność z przeglądarkami. Możesz spróbować pliku moment.js.Twoja zmienna scope effectiveDate powinna zawierać obiekt Date. –

Odpowiedz

1

Jeśli chcesz korzystać z komponentów bootstrap w kątowe, musisz utworzyć dyrektywę lub możesz ponownie użyć niektórych istniejących, takich jak http://angular-ui.github.io/bootstrap/#/datepicker

przykład wykorzystania startowej wybór daty ze kątowe:

<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

uruchomiony w dokładny ten sam problem i ostatecznie rozwiązany, pisząc a n Angular http interceptor. Analizuje odpowiedź serwera i konwertuje wszystkie ciągi Datetime z formatem ISO/UTC na rzeczywiste obiekty daty JavaScript. Umożliwia to bezpośrednie powiązanie z datepicker i rozwiązuje problemy z weryfikacją.

Oto client-side kod kątowe, składający się z fabryce (Interceptor) i config części dla zapewnienia przechwytywania 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 
    }]); 

Po stronie serwera I skonfigurowany Newtonsoft.Json do serializacji terminy wykorzystujące format ISO z UTC strefy czasowej, który jest formatem przetestować przeciwko w kolektora:

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

Przechwytywacz jest na szczęście oparty na kodzie z Automatic JSON date parsing with AngularJS i AngularJS HTTP Date Interceptor Factory.

Powiązane problemy