在Javascript AngularJS中确定旧帖子的新帖子,是否过滤

时间:2014-09-24 04:06:43

标签: javascript php wordpress angularjs

好的,我正在使用WordPress和JSON API将WordPress作为我的应用程序的后端,现在我正在处理从帖子中获取日期并添加课程如果帖子是新的或不是,我很想知道这是不是过滤器的工作或只是扩展对象以添加新的属性,基本上迭代帖子数组并添加isNew的属性

虽然无法理解我的逻辑。

让我们说我从Post服务获得帖子

$scope.posts = [];
Post.getPosts().then(function(posts){
  $scope.posts = posts;
});

在我这样做之前:$ scope.posts = posts,我希望Angular扩展每个帖子的属性,添加isNew

var today = new Date();
var newMark = new Date();
newMark.setDate(newMark.getDate() - 5);

Post.getPosts(5).then(function (re) {
  angular.forEach(re.posts, function(post, key){
    var postDate = new Date(post.date);
    console.log(today - postDate < newMark); // lol, I don't have quite a logic here.
    // console.log(postDate - today < today - newMark);
  });
});
大笑,今天似乎无法思考。

2 个答案:

答案 0 :(得分:3)

您希望将所有发布日期都在newMark之后的帖子的属性设置为true,不是吗?

$scope.posts=[];
var newMark=new Date(Date.now() - 5 * 24 * 3600 *1000);

Post.getPosts(5)
.then(function (re) {
  // add a property to the model to tell whether is new 
  $scope.posts= re.posts.map(function(post){
    post.isNew=new Date(post.date) >= newMark;
    return post;
  });
});

现在,您可以将posts集合绑定到您的视图,并将ngClass指令与isNew属性一起使用,例如

答案 1 :(得分:1)

包括moment.js

Post.getPosts(5).then(function (re) {
  var newMark = moment().subtract(5, 'days');
  for (var i in re.posts) {
    re.posts[i].isNew = moment(post.date) > newMark ? true : false;
  }
});