How to filter JSON data based on current date

2019-07-15 12:20发布

问题:

I wanna ask about angularJS.

I have json here

var friends = [
{
"id":1,
"Tanggal":"\/Date(1408060800000)\/",
"Nama":"Hari Departemen Agama Republik Indonesia"
},
{
"id":2,
"Tanggal":"\/Date(1388880000000)\/",
"Nama":"Hari Korps Wanita Angkatan Laut"
},

View

 <ul>
   <li ng-repeat="friend in friends | filter:" >{{friend.Tanggal.substr(6,13) | date: 'dd MMMM' }}
    {{friend.Nama}}
   </li>
 </ul>

this my controller

.controller('FriendsCtrl', function($scope, Friends) {

 $scope.friends = Friends.all();

 })

I want to filter variable "Tanggal" to show data as current date(today). so just data on today will show.

Need help.

回答1:

You can use a custom filter for that:

app.filter('todayFilter', function() {
  return function(items, field) {

    var newItems = [];

    var currentDate = new Date();
    var tomorrow = new Date();

    currentDate.setHours(0, 0, 0, 0);
    tomorrow.setDate(currentDate.getDate() + 1);

    angular.forEach(items, function(item) {
      if (item[field] >= currentDate && item[field] <= tomorrow) {
        newItems.push(item);
      }
    });

    return newItems;
  }
});

And apply it like this:

<ul>
  <li ng-repeat="friend in friends | todayFilter: 'Tanggal'" >{{friend.Tanggal.substr(6,13) | date: 'dd MMMM' }}
    {{friend.Nama}}
  </li>
</ul>

That way you can reuse your filter in other parts of your app.

Here is a plunker demonstrating that: http://plnkr.co/edit/qga1POO1nV0kaEzXUuFH?p=preview

Hope that helps.