AngularJS Vertical ng-repeat

Say we have an array of people in JSON format. Each object has about 100 attributes. Standard approach for using ng-repeat:

...
<tr>
  <th>Attribute1</th>
  <th>Attribute2</th>
  ...
  <th>AttributeN</th>
</tr>
...
<tr ng-repeat="obj in jsonArray">
  <td>{{ obj.attr1 }}</td>
  <td>{{ obj.attr1 }}</td>
  ...
  <td>{{ obj.attrN }}</td>
</tr>

Which creates the following table:

Attribute1 | Attribute2 | ... | AttributeN
------------------------------------------
value1.1   | value1.2   | ... | value1.N
value2.1   | value2.2   | ... | value2.N
...
valueN.1   | valueN.2   | ... | valueN.N

Instead, I need:

Attribute1 | value1.1 | value2.1 | ... | valueN.1
Attribute2 | value1.2 | value2.2 | ... | valueN.2
...        | ...      | ...      | ... | ...
AttributeN | value1.N | value2.N | ... | valueN.N

So the question is: how do I achieve this?

  • Without manipulation of the "hands" (js-jQuery), without leaving the world of angular, there will be event handlers, etc.
+4
source share
3 answers

If I understand correctly what you are trying to achieve, then you will do it:

<table>
  <tr ng-repeat="(key, value) in people[0]">
    <th>{{key}}</th>
    <td ng-repeat="person in people">
      {{person[key]}}
    </td>
  </tr>
</table>

Assuming your data is an array of objects with the same properties, you iterate over the first object in the array to get the keys, which would make the headers of the vertical tables.

. , :

http://jsfiddle.net/andreiho/huL8pvmg/1/

, , . . , .

+3

jsonArray .

DEMO

Javascript

.controller('DemoController', function(Data, $scope) {

  Data.all().then(function(response) {
    $scope.indexedObjects = indexByAttribute(response.data);
  });

  function indexByAttribute(collection) {
    return collection.reduce(function(result, item) {

      angular.forEach(item, function(value, index) {
        result[index] = result[index] || [];
        result[index].push(value);
      });

      return result;
    }, {});
  }

});

HTML

<table>
  <tr ng-repeat="(index, values) in indexedObjects track by index">
    <th>{{ index }}</th>
    <td ng-repeat="value in values track by $index">
      {{ value }}
    </td>
  </tr>
</table>
+2

filter.

yourModule.filter('myFilter', [ function (arr) {
    var newArr = [];
    // loop over arr and construct newArr as you wish
    ... 

    return newArray;
} ])

`

<tr ng-repeat="obj in (jsonArray | myFilter)">
    <td>{{ obj.attr1 }}</td>
    <td>{{ obj.attr2 }}</td>
    ...
    <td>{{ obj.attrN }}</td>
</tr>

This way, ng-repeat will convert your jsonArray to a newly formed array and use it in a loop, but you still won't have jsonArray if you use it elsewhere.

+1
source

Source: https://habr.com/ru/post/1620297/


All Articles