ygesher
ygesher

Reputation: 1161

Double ng-repeat to flatten out nested object

I have a use in case which I had solved up 'til now with ng-repeat-start. It currently looks like this:

Controller

$scope.providers = [
  'Site Hosting',
  'Best Hosting',
  'Fantastic Hosting'
];

$scope.providerColumns = {
  price: {
    text: 'Price',
    exposed: true
  },
  site: {
    text: 'Website',
    exposed: true
  },
  phone: {
    text: 'Phone Number',
    exposed: false
  }
};

Template

<div class='table-header-row'>
  <div class='first-header-cell' ng-repeat='obj in firstCellsHeaders'>
    {{obj.text}}
  </div>
  <div class='middle-header-cell' ng-repeat-start='prov in providers' ng-if='providerColumns.price.exposed'>
    {{prov}} {{providerColumns.price.text}}
  </div>
  <div class='middle-header-cell' ng-if='providerColumns.site.exposed'>
    {{prov}} {{providerColumns.site.text}}
  </div>
  <div class='middle-header-cell' ng-repeat-end ng-if='providerColumns.phone.exposed'>
    {{prov}} {{providerColumns.phone.text}}
  </div>
  <div class='last-header-cell' ng-repeat='obj in lastCellsHeaders'>
    {{obj.text}}
  </div>
</div>
<div class='table-row'>
  <div class='first-cells' ng-repeat='obj in firstCells'>
    {{obj.text}}
  </div>
  <div class='middle-cells' ng-repeat-start='prov in providers' ng-if='providerColumns.price.exposed'>
    {{data[prov].price}}
  </div>
  <div class='middle-cells' ng-if='providerColumns.site.exposed'>
    {{data[prov].site}}
  </div>
  <div class='middle-cells' ng-repeat-end ng-if='providerColumns.phone.exposed'>
    {{data[prov].phone}}
  </div>
  <div class='last-cells' ng-repeat='obj in lastCells'>
    {{obj.texLine2}}
  </div>
</div>

It's essentially a table built out of div's in order to facilitate reordering the columns after angular finishes rendering.

Now I've realized the object represented in ng-repeat-start is more dynamic than I previously thought, and I want to be able to have a squared ng-repeat, i.e. nested repeat without nested elements, much like the oft-applied solution of using ng-repeat on a tbody element, and then an additional ng-repeat on the tr elements within it, which essentially is a flattened nesting effect. I need a solution for horizontal elements, preferably divs. I can't have them tied together in any way, however, so no nesting of divs or anything like that. Ideally it would look something like this:

<div ng-repeat='prov in providers' ng-repeat='col in providerColumns' ng-if='col.exposed'>
  {{data[prov][col]}}
</div>

Any ideas?

Upvotes: 1

Views: 532

Answers (1)

Cosmin Ababei
Cosmin Ababei

Reputation: 7072

Instead going with:

<div ng-repeat='obj1 in parent' ng-repeat='obj2 in obj1'>
    {{content[obj1][obj2]}}
</div>

Why not use a nested ngRepeat, like this:

<div ng-repeat='obj1 in parent'>
    <div ng-repeat='obj2 in obj1'>
        {{content[obj1][obj2]}}
    </div>
</div>

Upvotes: 1

Related Questions