Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS Date filter not working

I have an ng-repeat element which will loop through $http.get() result.

<tr ng-repeat="blog in posts">
     <td style="text-align:center">{{ $index+1 }}</td>
     <td>{{ blog.title }}</td>
     <td>
         {{ blog.author.name }}
     </td>
     <td>
         {{ blog.created_at | date:'MMM-dd-yyyy' }}
     </td>
</tr>

I have created_at as timestamp in MySQL database table. And I am using angular.js v1.0.7.

I am getting the same output from db table and date filter is not working. How can I solve this?

My ajax call,

$http({method: 'GET', url: 'http://localhost/app/blogs'}).
success(function(data, status, headers, config) {
    $scope.posts = data.posts;
}).
error(function(data, status, headers, config) {
    $scope.posts = [];
});
like image 649
Anshad Vattapoyil Avatar asked Oct 29 '13 08:10

Anshad Vattapoyil


2 Answers

The date passed to the filter needs to be of type javascript Date.

Have you checked what the value blog.created_at is displayed as without the filter?

You said your backed service is returning a string representing the date. You can resolve this in two ways:

  1. Make your server-side code return a json date object
    • check how the server side code serialize the json that it returns
  2. Write your own filter which accepts the string date and returns date in the required format
    • Note: you can call the angular filter in your own filter

You can write your own filter as follows:

app.filter('myDateFormat', function myDateFormat($filter){
  return function(text){
    var  tempdate= new Date(text.replace(/-/g,"/"));
    return $filter('date')(tempdate, "MMM-dd-yyyy");
  }
});

And use it like this in your template:

<td>
  {{ blog.created_at | myDateFormat }}
</td>

Rather than looping through the returned array and then applying the filter

like image 70
Anoopsingh Bayes Avatar answered Nov 06 '22 15:11

Anoopsingh Bayes


From the server side, it returns the created_at as string from the laravel eloquent.

This can be solved using this javascript,

new Date("date string here".replace(/-/g,"/"));

So the code,

$http({method: 'GET', url: 'http://localhost/app/blogs'}).
success(function(data, status, headers, config) {
   angular.forEach(data.posts, function(value, key){
     data.posts[key].created_at = new Date(data.posts[key].created_at.replace(/-/g,"/"));
   }
   $scope.posts = data.posts;
}).
error(function(data, status, headers, config) {
    $scope.posts = [];
});
like image 15
Anshad Vattapoyil Avatar answered Nov 06 '22 15:11

Anshad Vattapoyil