【问题标题】:Why won't ng-repeat work with ng-if?为什么 ng-repeat 不能与 ng-if 一起使用?
【发布时间】:2016-03-01 15:30:58
【问题描述】:

我正在尝试使用 Angular 1.4.8 填充表格。

为什么这不起作用...

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

...但这吗?

<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>

我的代码如下。

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>

【问题讨论】:

  • 正在使用没有 ng-if {{ celda }}?
  • 我添加了一个代码 sn-p 以便其他人也可以运行此代码并看到您描述的相同类型的东西。

标签: angularjs angularjs-ng-repeat angular-ng-if


【解决方案1】:

中继器中有重复项。将 $index 的曲目添加到您的 ng-repeat="celda in fila":

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

小提琴:http://jsfiddle.net/1z04c00u/

见文档:https://docs.angularjs.org/error/ngRepeat/dupes

【讨论】:

  • 顺便说一句:您可以将上面的 sn-p 复制到您的答案中,您可以看到它运行和执行,而无需外部站点来托管代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多