0

i'm trying to order a json array using angularjs using timestamp, but its not working for somereson

<div ng-repeat="post in posts track by post.id|orderBy:'post_date':reverse" class="list-group-item apost">
  <h4 class="timeline-title">{{post.title}}</h4>
</div>

js

$scope.Posts = [
  {"id":1,"user_id":1,"title":"Welcome to MRI","body":"\u0641\u064a \u062d\u0627\u0644\u0647 \u0627\u064a \u0627\u0633\u062a\u0641\u0627","post_date":1422929860,"fullname":"MZ"},
  {"id":3,"user_id":1,"title":"\u0641\u064a \u062d\u0627\u0644\u0647 \u0636\u0627,","post_date":1422933651,"fullname":"MZ"},
  {"id":24,"user_id":1,"title":"\u0641\u064a \u062d\u0627\u0644\u0647 \u0627\u064a \u0627\u0633\u062a\u0641\u0633\u0627\u0631","body":"\u0628\u0631\u0631","post_date":1425404937,"fullname":"Mz"},
  {"id":29,"user_id":1,"title":"new post","body":"fk shit mf","post_date":1425405333,"fullname":"MZ"}
]

i want to show newest posts first.

also is it possible to check if the post_date is today in angular template to apply a special class ?

1

1 Answer 1

1

According to this answer, you have to use track by after your orderBy statement.

And from ngRepeat documentation (see 'Arguments' table):

For example: item in items | filter:searchText track by item.id is a pattern that might be used to apply a filter to items in conjunction with a tracking expression.

Based on this info I think you want to use something like:

post in posts | orderBy:'post_date':true track by post.id

also is it possible to check if the post_date is today in angular template to apply a special class ?

For this you could define a function to check if your value is today in $scope.

Angular JS:

.controller("PostCtrl", function($scope) {

    $scope.isToday = function(date) {
       /**
        * Logic to determine if date is today or not goes here.
        * Will either return true or false.
        */
    };
})

Then within your HTML template, you can pass each post's date into isToday. If it returns true then your specialClass will get applied.

HTML:

<div ng-repeat="post in posts | orderBy:'post_date':true track by post.id" class="list-group-item apost">
  <h4 class="timeline-title" ng-class="{specialClass: isToday(post.post_date)}">{{post.title}}</h4>
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

thanks that worked !. i also had to change :reverse to :true and that solved the problem :) angular 1.3
@Zalaboza I attempted to answer the second part of your question. Let me know if it's not clear to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.