【问题标题】:ng-repeat vertically and horizontally in a table when receiving dynamic datang-repeat 接收动态数据时在表格中垂直和水平重复
【发布时间】:2019-01-04 15:59:32
【问题描述】:

我正在尝试在表格中显示数据。
行和列是动态的。
我想使用ng-repeat

我正在以这种形式接收数据:

headers: [
  0: {"heading1"},
  1: {"heading2"},
  2: {"heading3"}
]
data: [
  0:{ id:1, code:"Barry" , description:"Allen" }
  1:{ id:2, code:"Naruto" , description:"Uzumaki" }
  2:{ id:3, code:"Hannah" , description:"Montana" }        
] 

我试过这样:

<thead>
  <tr>
    <td ng-repeat="c in headersData">
      {{c}}
    </td>
  </tr>
</thead>
<tbody>
  <tr ng-repeat="c in columnData">
    <td>{{c.id}}</td>
    <td>{{c.code}}</td>
    <td>{{c.description}}</td>
  </tr>
</tbody>

但它不会渲染thead
有什么解决办法吗?

【问题讨论】:

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


    【解决方案1】:

    当你收到一个像 headers 一样的数组时,你必须为键值对定义一个 var 名称。试试这个:

    <thead>
      <tr>
        <td ng-repeat="(key,c) in headersData">
          {{c}}
        </td>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="c in columnData">
        <td>{{c.id}}</td>
        <td>{{c.code}}</td>
        <td>{{c.description}}</td>
      </tr>
    </tbody>
    

    【讨论】:

      【解决方案2】:

      var app = angular.module('testApp',[])
      app.controller('MainController',function($scope) {
         $scope.headersData =  [
       "heading1",
       "heading2",
       "heading3"
      ];
       $scope.columnData =  [
        { id:1, code:"Barry" , description:"Allen" },
        { id:2, code:"Naruto" , description:"Uzumaki" },
        { id:3, code:"Hannah" , description:"Montana" }        
      ] ;
      });
      <!DOCTYPE html>
      <html ng-app="testApp">
      
      <head>
        <script data-require="angular.js@*" data-semver="4.0.0" 
        src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js">
        </script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
      
      <body ng-controller="MainController">
       <table>
        <tr>
          <th ng-repeat="th in headersData">{{th}}</th>
        </tr>
        <tr ng-repeat="x in columnData">
          <td>{{x.code}}</td>
        </tr>
      </table>
      </body>
      
      </html>

      【讨论】:

        【解决方案3】:

        首先,这是一种错误的做法。 有一种方法可以使用ng-repeat="(key,value) in yourjson 格式。

        所以先检查一下。

        而且您的标题不应该以这种方式声明。或者换句话说,不应该以这种方式呈现。你正在做c in headers 这会给你对象。 {heading1 } 等等。 这是一个非常基本的问题,Stack Overflow 中已经提供了很多答案。

        所以做一些类似的事情, ng-repeat="x in headers"

        并将您的标题定义为 headers= ["heading1","heading2","heading3"] 因为您声明的不是有效的 JSON。

        要检查JSON的有效性,您可以查看JsonLint

        【讨论】:

          猜你喜欢
          • 2014-07-11
          • 1970-01-01
          • 2011-01-12
          • 1970-01-01
          • 2012-05-11
          • 2011-08-12
          • 1970-01-01
          • 1970-01-01
          • 2012-12-16
          相关资源
          最近更新 更多