redshift
redshift

Reputation: 5217

AngularJS: Date will not filter correctly when consuming JSON feed

I am trying to display a JSON feed from Wordpress using AngularJS and I have it working pretty good, except I can't figure out why my date filter is not working.

It seems that no matter what I do, the date won't filter to the format specified.

I am trying to format the date so it displays as: "July 1, 2015", but it's being parsed as "July 1, 2015 23:40" despite using the "date: 'longDate'" filter in my HTML expression.

Is it because I'm using the same date variable in the JSON feed AND the angular expression?

Here's my code:

<div ng-app="myApp" ng-controller="Ctrl"> 

<div ng-repeat="post in posts | limitTo: 2">
<h1>{{post.title}}</h1>
<p>{{ post.date | date:'longDate' }}</p>
<p>{{post.content | limitTo: 50}}</p>
</div>

</div>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('Ctrl', function($http, $scope) {
$http.get("http://www.intecllc.net/wp/?feed=json&jsonp").success(function(data) {
    $scope.posts = data;
    });
});
 </script>
 </body>
</html>

here's what the parsed JSON feed looks like: sample page and you can see that the date does not get affected by the angular 'longDate' filter.

Upvotes: 0

Views: 206

Answers (1)

callmekatootie
callmekatootie

Reputation: 11228

The error that you get is because the date property returned by your server does not seem to be in a format that the date filter can understand.

Instead, loop over the data to replace the date value with the actual date object:

//This code goes in the success handler:
for (var i =0; i < $scope.posts.length; i++) {
    $scope.posts[i].date = new Date($scope.posts[i].date);
}

Using the new Date() you update the date property to contain valid date object. The Date() constructor accepts your string and returns a proper date object.

After this, you can indeed use the {{post.date | date:'longDate'}} filter and it shows up correctly. Plunkr showing that it works.

Upvotes: 1

Related Questions