How to filter JSON data based on current date

孤人 提交于 2019-12-24 02:26:11

问题


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.



来源:https://stackoverflow.com/questions/25349940/how-to-filter-json-data-based-on-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!