繁体   English   中英

使用Angular.js创建表

[英]Creating tables with Angular.js

我正在尝试使用Angular.js创建一个表格,该表格将包含跨越多行的单元格。

例:

http://jsfiddle.net/famedriver/kDrc6/

示例数据

var data = [{Colors: ["red","green","blue"]}]

预期产出

<table>
  <tr>
    <td rowspan="3">Colors</td>
    <td>red</td>
  </tr>
  <tr>
     <td>green</td>
  </tr>
  <tr>
     <td>blue</td>
  </tr>
 </table>

我使用ng-show指令工作。 但这仍然是一个额外的细胞,只是隐藏。 使表格正确呈现是理想的。

如上所述, ng-switch在某些具有严格解析的元素中不起作用(即:只允许某些标记的表)

有什么建议?

通常你可以使用ng-switch这样的东西,它有条件地添加/删除DOM中的东西,不像ng-show / ng-hide只是隐藏/显示东西。

但ng-switch对表不好用,因为它需要一个额外的switch语句元素。

幸运的是,有人制作了一个名为'if'的指令,它只对元素采用一个属性并有条件地从DOM中添加/删除它。 这是天才:-)。

这是一个例子(在侧面的'Resources'面板中查看,我从github中包含它)。 http://jsfiddle.net/5zZ7e/

我还展示了如何在没有全局变量的情况下制作控制器。

使用更新版本的Angular回答问题。

正如Andrew Joslin写的那样, ng-show隐藏了元素(它应用display: none )。 ng-switch删除不匹配的元素而不是隐藏它们。 但它也需要额外的元素用于switch-when表达式。

从上一个答案开始, ng-if已成为Angular的一部分,您不再需要外部库。

 (function(win) { angular.module('myApp', []) .controller("Tester", function($scope) { $scope.data = { Colors: ["red", "green", "blue"] } }) }(window)); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <div ng-app="myApp"> <h1>old code converted</h1> <p>Just converted to a newer AngularJS.</p> <table border="1" ng-controller="Tester"> <tbody ng-repeat='(what,items) in data'> <tr ng-repeat='item in items'> <td rowspan="{{items.length}}" ng-show="$first">{{what}}</td> <td>{{item}}</td> </tr> </tbody> </table> <h1>solution via ng-if</h1> <table border="1" ng-controller="Tester"> <tbody ng-repeat='(what,items) in data'> <tr ng-repeat='item in items'> <td rowspan="{{items.length}}" ng-if="$first">{{what}}</td> <td>{{item}}</td> </tr> </tbody> </table> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM