【问题标题】:How to use ng-repeat and filter to hide some columns in a dynamic table?如何使用 ng-repeat 和 filter 隐藏动态表中的某些列?
【发布时间】:2017-06-08 16:11:48
【问题描述】:

我有一个从数据库返回的动态数据集,我正在尝试为其创建一个可以始终列出它的通用表,无论列数或行数。

它工作正常,但我遇到的问题是我希望能够隐藏一些列,例如 ID。

这是数据的样子:

scope.columns = [
    {
        'Name': 'ID',
        Visible: false,
    },
    {
        'Name': 'Name',
        Visible: true,
    },
    {
        'Name': 'Description',
        Visible: true,
    },
];

scope.rows = [
    {
        ID: 1, // should be hidden because ID column above is set to Visible - false
        Name: 'Test',
        Description: 'Its a test',
    },
    {
        ID: 2, // should be hidden because ID column above is set to Visible - false
        Name: 'Test 2',
        Description: 'Its a test 2',
    }
];

这是HTML table 一代:

<table class="table">
    <!-- This part works fine and doesn't show some of the columns -->
    <tr>
        <th ng-repeat="column in columns | filter: { Visible: 'true'}">
            <span ng-bind="column.Name"></span>
        </th>
    </tr>
    <tr ng-repeat="row in rows">
        <td ng-repeat="col in row"> <!-- This is the part where I need filter the cols based on the column.Visible above -->
            {{col}}
        </td>
    </tr>
</table>

我尝试在&lt;td&gt; 上添加过滤器,但我不确定如何根据scope.columns 数组进行过滤。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-repeat


    【解决方案1】:

    您可以使用 ng-if -> ng-if="columns[$index].Visible" 在您的情况下执行此操作,例如 DEMO FIDDLE。您在$scope.rows 中的属性顺序必须与$scope.columns 中的相同,以确保其正常工作。

    <div ng-controller="MyCtrl">
      <table class="table">
        <!-- This part works fine and doesn't show some of the columns -->
        <tr>
          <th ng-repeat="column in columns | filter: { Visible: true}">
            <span ng-bind="column.Name"></span>
          </th>
        </tr>
        <tr ng-repeat="row in rows">
          <td ng-repeat="col in row" ng-if="columns[$index].Visible">
            {{col}}
          </td>
        </tr>
      </table>
    </div>
    

    【讨论】:

    • 太好了,谢谢。我完全忘记了$index
    • @Apostrofix 很高兴为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    相关资源
    最近更新 更多