Tablas AngularJS


La directiva ng-repeat es perfecta para mostrar tablas.


Mostrar datos en una tabla

Mostrar tablas con angular es muy simple:

Ejemplo de AngularJS

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("customers.php")
  .then(function (response) {$scope.names = response.data.records;});
});
</script>

Visualización con estilo CSS

Para hacerlo agradable, agregue algo de CSS a la página:

Estilo CSS

<style>
table, th , td {
  border: 1px solid grey;
  border-collapse: collapse;
  padding: 5px;
}

table tr:nth-child(odd) {
  background-color: #f1f1f1;
}

table tr:nth-child(even) {
  background-color: #ffffff;
}
</style>


Mostrar con orderBy Filter

Para ordenar la tabla, agregue un filtro orderBy

Ejemplo de AngularJS

<table>
  <tr ng-repeat="x in names | orderBy : 'Country'">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

Pantalla con filtro de mayúsculas

Para mostrar mayúsculas, agregue un filtro  de mayúsculas :

Ejemplo de AngularJS

<table>
  <tr ng-repeat="x in names">
    <td>{{ x.Name }}</td>
    <td>{{ x.Country | uppercase }}</td>
  </tr>
</table>

Mostrar el índice de la tabla ($index)

Para mostrar el índice de la tabla, agregue un <td> con $index

Ejemplo de AngularJS

<table>
  <tr ng-repeat="x in names">
    <td>{{ $index + 1 }}</td>
    <td>{{ x.Name }}</td>
    <td>{{ x.Country }}</td>
  </tr>
</table>

Usando $par y $impar

Ejemplo de AngularJS

<table>
  <tr ng-repeat="x in names">
    <td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
    <td ng-if="$even">{{ x.Name }}</td>
    <td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
    <td ng-if="$even">{{ x.Country }}</td>
  </tr>
</table>