【问题标题】:AngularJS: Table with ng-repeat on table row / columnAngularJS:表格行/列上带有 ng-repeat 的表格
【发布时间】:2017-11-07 12:21:24
【问题描述】:

我需要从一组对象创建一个表,但我不想对表进行硬编码。例如,我不能做thisthis。我宁愿需要像 this 这样的嵌套 ng-repeats。但我的情况有点不同,因为我的列包含数组中的两个值。数据如下所示:

[
   {
      "foo":"bar",...,
      "key1":[
         "value1",
         "value2"
      ],
      "key2":[
         "value1",
         "value2"
      ],...,
      "more_foo":"more_bar"
   },...
]

我想要表行中的数组中所有对象(始终具有相同结构)的值(始终是字符串),其中每个键都应该是列名。像这样:

table,
th,
td {
  border: 1px solid black;
  text-align: center;
  border-spacing: 0;
}

td,
th {
  padding: 0.5em;
}
<table>
  <thead>
    <tr>
      <th>foo</th>
      <th colspan="2">key1</th>
      <th colspan="2">key2</th>
      <th>more_foo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>bar</td>
      <td>value1</td>
      <td>value2</td>
      <td>value1</td>
      <td>value2</td>
      <td>more_bar</td>
    </tr>
  </tbody>
</table>

这是我想出的:

<table>
    <thead>
    <tr>
        <th ng-repeat="(propName, prop) in myArray[0]"
            colspan="{{isUpdateable(propName) ? 2 : undefined}}"> {{propName}}
        </th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="object in myArray | filter: searchFilter">
        <td ng-repeat="(propName, prop) in object" double-col>{{prop}}</td>
    </tr>
    </tbody>
</table>

isUpdatable(propName) 如果此值是一个数组,则返回 true,否则返回 false。这样就可以在此列中有两个tds。

双列指令:

app.directive('double-col', function () {
    return {
        transclude: true,
        template: "<td>{{prop[0]}}</td><td class=\"changedProp\">{{prop[1]}}</td>"
    };
});

当且仅当prop 是一个数组时,我希望该指令用两个tds 替换现有的td,否则不执行任何操作来显示prop(参见上面的td)。

因为你在https://stackoverflow.com(人们发布还不能正常工作的东西的地方),你可能会猜到我当前的代码不能很好地工作。我也是 angularJS 的新手,基本上不了解自定义指令(可能还有大多数其他东西),所以如果有人能帮助我解决这个问题并提供解释,那就太好了。

【问题讨论】:

    标签: angularjs angularjs-directive html-table angularjs-ng-repeat custom-directive


    【解决方案1】:

    怎么样

    <tr ng-repeat="object in myArray | filter: searchFilter">
            <td ng-repeat="(propName, prop) in object" colspan="{{isArray(prop) ? prop.length : 1}}">
           <span ng-if="!isArray(prop)"> {{prop}}</span>
            <table ng-if="isArray(prop)"><tr>
        <td ng-repeat="prop1 in prop">
            {{prop1}}
        </td>
       </tr></table>
            </td>
    
        </tr>
    
    $scope.isArray=function(prop){
    return Array.isArray(prop);
    }
    

    Here is working fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-26
      • 2023-04-04
      • 2014-10-30
      • 1970-01-01
      • 2023-03-04
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多