0

I need to display a list of messages with a "header" which contain only de date of the messages below, something like this:

2014-12-24
Message 1
Message 2
Message 3
2014-12-21
Test 1
Test 2

etc.

I have the follow json:

[
    {
        created_at: "2014-12-24",
        message: "Message 1"
    },
    {
        created_at: "2014-12-24",
        message: "Message 2"
    },
    {
        created_at: "2014-12-24",
        message: "Message 3"
    },
    {
        created_at: "2014-12-21",
        message: "Test 1"
    },
    {
        created_at: "2014-12-21",
        message: "Test 2"
    },
]

How can I do that during iteration in a template using AngularJS?

Thanks!!

2 Answers 2

1

You can display created_at only when this value is not the same as previous one.

   <h3 ng-if="data[$index-1].created_at != item.created_at">
        {{item.created_at}}
   </h3>

And you have to sort your data. E.g.

$scope.data = $filter('orderBy')($scope.data, 'created_at', true);

But ofc, you should improve sorting because 'created_at' property is string (not date).

Example http://jsfiddle.net/t4z1joj5/

Sign up to request clarification or add additional context in comments.

Comments

1

you can use https://lodash.com/docs#groupBy

var json = [
    {
        created_at: "2014-12-24",
        message: "Message 1"
    },
    {
        created_at: "2014-12-24",
        message: "Message 2"
    },
    {
        created_at: "2014-12-24",
        message: "Message 3"
    },
    {
        created_at: "2014-12-21",
        message: "Test 1"
    },
    {
        created_at: "2014-12-21",
        message: "Test 2"
    },
];

var data = _.groupBy(val, 'created_at');

It will group your json array by created_at value.

Comments

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.