【问题标题】:Can you populate a table with Angular.js without hardcoding column names?你可以在没有硬编码列名的情况下用 Angular.js 填充表吗?
【发布时间】:2016-02-01 02:57:56
【问题描述】:

我有一个简单的 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 填充表格,如果可以,那么最有效的方法是什么?

【问题讨论】:

标签: javascript mysql angularjs twitter-bootstrap


【解决方案1】:

您可能想试试这个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>

【讨论】:

    猜你喜欢
    • 2011-11-30
    • 2012-02-08
    • 2020-09-29
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多