Data array reorganization for display

Asked

Viewed 76 times

0

I’m creating an application using AngularJs and skeleton, I have the layout set up, now I’m on the part of making it dynamic, but I’m facing a basic little problem. I have the following array coming from the back-end:

[
    0 => [
        'title'         => 'Um titulo aqui',
        'slug'          => 'Aqui-o-slug',
        'categoria_id'  => 17
    ],
    1 => [
        'title'         => 'Um titulo aqui',
        'slug'          => 'Aqui-o-slug',
        'categoria_id'  => 12
    ],
    2 => [
        'title'         => 'Um titulo aqui',
        'slug'          => 'Aqui-o-slug',
        'categoria_id'  => 4
    ]
]

The layout holds 4 elements of the array, every 4 I have to put inside a new "Row" not to break the layout. What I want to know is which way I could do this, which functions and so on, I want to make the code as simple as possible.

Note: Use php in the back-end.

1 answer

1


At the angle, there is the property ng-repeat that will repeat a code block for each object in your array. See an example:

<li ng-repeat="dados in $scope.minhaArray">{{dados.categoria_id}} - {{dados.title}}</li>

That would generate the following html:

<li>17 - Um título aqui</li>
<li>12 - Um título aqui</li>
<li>4 - Um título aqui</li>

Your problem is that you need to repeat inside a row 4 objects of the array, but the ng-repeat does not do this. I believe you have 2 solutions:

  • Change your layout; Simpler and less error-prone.
  • Change your array; more 'complex' and more error-prone.

The layout change doesn’t have much to say, it would have to adapt so that it fits your needs and it is possible to use the ng-repeat.

The array change would be more complex. You would need to generate an array within an array, where each child-array contains only 4 objects, leaving an array +- like this:

[
    {data1: [
        {categoria_id: 1, title: 'um titulo aqui'},
        {categoria_id: 2, title: 'um titulo aqui'},
        {categoria_id: 3, title: 'um titulo aqui'},
        {categoria_id: 4, title: 'um titulo aqui'}
           ]
    },
    {data2: [
        {categoria_id: 5, title: 'um titulo aqui'},
        {categoria_id: 6, title: 'um titulo aqui'},
        {categoria_id: 7, title: 'um titulo aqui'},
        {categoria_id: 8, title: 'um titulo aqui'}
           ]
    },
    {data3: ...etc...
]

So you could have an html this way:

<div class="row" ng-repeat="data in $scope.minhaLista">
    <div class="bloco" ng-repeat="dados in data">
        {{dados.categoria_id}} - {{dados.title}}
    </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.