您可以使用 Angular 填充表.js而无需硬编码列名

Can you populate a table with Angular.js without hardcoding column names?

本文关键字:编码 js 可以使 Angular 填充      更新时间:2023-09-26

我有一个简单的Angular.js应用程序,它从mysql数据库中获取表格数据并将其显示在一个简单的引导表中。我正在使用下面的代码来显示表列名称,而无需单独硬编码它们......

HTML:
       <table class="table">
        <thead>
          <tr style="background:lightgrey">
             <th ng-repeat="column in columns"> {{ column }} </th>
          </tr>
        </thead>

在控制器中,我用这样的东西创建了"$scope.columns"......

    var columnNames = function(dat) {
        var columns = Object.keys(dat[0]).filter(function(key) {
          if (dat[0].hasOwnProperty(key) && typeof key == 'string') {
            return key;
          }
        });
        return columns;
    };
    DataFactory.getTables(function(data) {
        $scope.columns = columnNames(data);
        $scope.tables = data; 
    });

这按预期工作,很棒,但是其余数据呢?例如,我的表格主体目前看起来像这样......

HTML:
       <tbody>
          <tr ng-repeat="x in tables ">
            <td> {{ x.id}} </td>
            <td> {{ x.name }} </td>
            <td> {{ x.email }} </td>
            <td> {{ x.company }} </td>
        </tbody>

我试过使用两个这样的循环...

HTML:
        <tbody>
          <tr ng-repeat="x in tables">
            <td ng-repeat=“column in columns”> {{ x.column }} </td>
          </tr>
        </tbody>

但是这段代码不起作用,那么是否可以在不对 HTML 中的列名进行硬编码的情况下用 angular 填充表,如果是这样,最有效的方法是什么?

您可能

想尝试此 https://jsfiddle.net/8w2sbs6L/。

<div data-ng-app="APP">
    <table ng-controller="myController" border=1>
    <thead>
        <tr>
          <td ng-repeat="column in columns">{{column}}</td>
        </tr>
    </thead>
        <tbody>
      <tr ng-repeat="x in tables">
        <td ng-repeat="column in columns">{{x[column]}}</td>
      </tr>
    </tbody>
    </table>
</div>

<script>
'use strict';
angular.module('APP', [])

.controller('myController', ['$scope', function($scope){
    $scope.tables = [
        { 
            "column1":"row1-column1",
        "column2":"row1-column2",
            "column3":"row1-column3",
            "column4":"row1-column4" 
        },
        { 
            "column1":"row2-column1",
        "column2":"row2-column2",
            "column3":"row2-column3",
            "column4":"row2-column4" 
        }
    ];
    $scope.columns = [
        "column1",
      "column2",
        "column3",
        "column4" 
    ];
}]);
</script>