[英]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.