0

Trying to append a GET URL with a date, but it needs to be in the format "yyyyMMdd00".

Despite trying all the solutions here:

AngularJS - convert dates in controller

and

Binding value to input in Angular JS

I can only ever produce dates in the medium style format: dateFrom%3DFri+Feb+24+2017+00%3A00%3A00+GMT%252B0000+%28GMT+Standard+Time%29

Or nothing appears.

HTML (the h3 produces what I want to add to my url):

     <ion-content class="item-input">
<label class="item-input">
    <span class="input-label">Date From</span>
    <input type="date" ng-model="dateFrom">
</label>
<h3>{{dateFrom | date: "yyyyMMdd00"}}</h3>

<a ui-sref="date({dateFrom:dateFrom})">Go</a>
</ion-content>

Controller

     .controller("DateCtrl", function ($scope, $stateParams, dateService) {
$scope.events = dateService.getEvents($stateParams.dateFrom).then(function (events) {
    $scope.events = events;

});

Factory:

      .factory('dateService', function ($http) {
    var events = [];

    return {
        getEvents: function (date) {
            var params = {
                dateFrom: date
            }

            return $http.get('URL', { params: params }).then(function (response) {
                events = response.data.events;
                return response.data.events;
            });

And finally the routing:

   .state('date', {
    url: "/date/:dateFrom",
    templateUrl: "templates/Date.html",
    controller: "DateCtrl"
})
Community
  • 1
  • 1
Kyle
  • 15
  • 5

1 Answers1

1

Use $urlMatcherFactoryProvider.type

Using type, you'll have access to decoded object in your controller etc.

Update state declaration a bit:

   .state('date', {
    url: "/date/{dateFrom:dateType}", // Use type "dateType" here
    templateUrl: "templates/Date.html",
    controller: "DateCtrl"
})

Include this in route file:

$urlMatcherFactoryProvider.type('dateType', {
  encode: function(date) {
    // Convert date object to URL format
    var format = 'yyyyMMdd00';
    return $filter('date')(date, format);
  },
  decode: function(dateStr) {
    // Convert URL date to date object
    var year = parseInt(dateStr.slice(0, 4));
    var month = parseInt(dateStr.slice(4, 6));
    var day = parseInt(dateStr.slice(6, 8));
    var date = new Date(year, month, day)
    return date;
  },
  is: function(item) {
    return true;
  }
});

Also, use moment.js for serializing and deserializing date, if you have it already included in your project.

Sangharsh
  • 2,999
  • 2
  • 15
  • 27
  • I'm new to all this - I can't seem to get it to work. Either its "urlmatcher not recognised" or the state doesn't change on click. I havent used moment - i'll take at a look at it. thank you! FYI - I'm using ionic, does that matter? – Kyle Feb 09 '17 at 19:53
  • Inject `$urlMatcherFactoryProvider` in your router config method – Sangharsh Feb 09 '17 at 19:55
  • I did that. Its still not doing anything. There's no error in console for me to report unfortunately. – Kyle Feb 09 '17 at 20:06