Marta Castro
Marta Castro

Reputation: 77

Why won't ng-repeat work with ng-if?

I'm trying to fill a table using Angular 1.4.8.

Why won't this work...

<td ng-if="fila" ng-repeat="celda in fila">{{ celda }}</td>

...but this does?

<td ng-if="fila">{{ fila[0] }}</td>
<td ng-if="fila">{{ fila[1] }}</td>
<td ng-if="fila">{{ fila[2] }}</td>
<td ng-if="fila">{{ fila[3] }}</td>

My code is below.

var app = angular.module('myApp', []);

app.controller('ctrlTest', function($scope) {

  $scope.tabla = {
    titulos: ['Caracteristicas', 'Opcion1', 'Opcion2', 'Opcion3', 'Opcion4'],
    datos: {
      'Caracteristica1': [25, 500, 500, 2500],
      'Separador': '',
      'Caracteristica2': ['-', 'X', 'X', 'X'],
      'Caracteristica3': ['-', '-', 'X', 'X']
    }
  };

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<div ng-app="myApp">
  <table ng-controller="ctrlTest">
    <tr>
      <th ng-repeat="titulo in tabla.titulos">{{ titulo }}</th>
    </tr>
    <tr ng-repeat="(clave,fila) in tabla.datos">
      <th ng-if="fila">{{ clave }}</th>
      <th ng-if="!fila" colspan="{{ (tabla.titulos).length }}">{{ clave }}</th>

      <td ng-if="fila" ng-repeat="celda in fila">{{ celda }}</td>
    </tr>
  </table>
</div>

Upvotes: 1

Views: 195

Answers (1)

Boris Parnikel
Boris Parnikel

Reputation: 863

You have duplicates in repeater. Add track by $index to your ng-repeat="celda in fila":

<td ng-if="fila" ng-repeat="celda in fila track by $index">{{ celda }}</td>

fiddle: http://jsfiddle.net/1z04c00u/

See doc: https://docs.angularjs.org/error/ngRepeat/dupes

Upvotes: 2

Related Questions