【问题标题】:Create HTML Table Using ng-repeat from Array使用数组中的 ng-repeat 创建 HTML 表
【发布时间】:2018-02-15 20:56:06
【问题描述】:

有人可以帮我使用 Angular JS ng-repeat 创建 HTML 表格吗?我有如下数组

cyclename = [cycle1,cycle2,cycle3]
passValue = [2,5,250]

使用这些我想生成 HTML 表格

<table>
  <tr>
    <td>cycle1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>cycle2</td>
    <td>5</td>
  </tr>
  <tr>
    <td>cycle3</td>
    <td>250</td>
  </tr>
</table>

我在 Angular JS 中尝试过如下但没有用

<table class="table">
    <tr ng-repeat="x in cyclename">
    <td>{{x}}</td>
    </tr>
    <tr ng-repeat="x in passValue">
    <td>{{x}}</td>
    </tr>
 </table>

【问题讨论】:

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


    【解决方案1】:

    简单的解决方案:

    <table>
        <tr ng-repeat="i in [0,1,2]">
            <td>{{cyclename[i]}}</td>
            <td>{{passValue[i]}}</td>
        </tr>
    </table>
    

    通过将值合并到像@sachila 的答案这样的对象中的“正常”解决方案。 如果您在将数组更改为对象时需要帮助:

    $scope.fullArr = cyclename.map(function(item, i) {
      return {
        cyclename: item,
        passValue: passValue[i]
      }
    })
    

    【讨论】:

      【解决方案2】:

      将你的数组修改为ine对象数组

      fullArr = [{cyclename :'cycle1',passValue : '2' },{cyclename :'cycle2',passValue : '5' },{cyclename :'cycle3',passValue : '250' }]
      
       <table class="table">
          <tr ng-repeat="x in fullArr">
          <td>{{x.cyclename}}</td>
          <td>{{x.passValue}}</td>
          </tr> 
       </table>
      

      【讨论】:

        【解决方案3】:

        这是最简单的一种方法,使用 $scope 并参考下面的代码

        控制器

         $scope.cyclename = ["cycle1","cycle2","cycle3"]
         $scope.passValue = [2,5,250]
        

        模板

        <table>
         <tr ng-repeat="x in cyclename">
           <td>{{x}}</td>
           <td>{{passValue[$index]}}</td>
         </tr>
        

        希望plunker 对您有所帮助

        【讨论】:

        • 请检查所需的结果html结构?
        • @Icycool 请告诉我 HTML 结构有什么问题?
        • 您的代码正在生成 &lt;tr&gt;&lt;td&gt;x3&lt;/tr&gt;x2 而不是 OP 要求的 &lt;tr&gt;&lt;td&gt;x2&lt;/tr&gt;x3
        • @Icycool 谢谢。我用 2 种表结构更新了 plunker。
        【解决方案4】:

        使用键值对合并两个数组并使用 ng-repeat

        cyclename = [cycle1,cycle2,cycle3]
        passValue = [2,5,250]
        
        to 
        
        mergerArr=[{
                     key:cycle1,
                     value:2
                    },{
                     key:cycle2,
                     value:5
                   }]
        

        Html 如下所示

        <table class="table">
        <tr ng-repeat="x in mergerArr">
        <td>{{x.key}}</td>
        <td>{{x.value}}</td>
        </tr>
        </table>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-12
          • 1970-01-01
          • 2015-02-23
          • 2014-09-14
          • 2015-12-23
          • 2017-03-24
          • 2020-02-20
          • 2016-08-31
          相关资源
          最近更新 更多