phi*_*tal 0 javascript angularjs angularjs-directive
我正在尝试使用Angular.JS动态地将列添加到html表中.
它从一组数据开始,我想在点击时提供额外的数据.我是Angular的新手,并且让这个用来说明我正在尝试做什么.我(显然)只是根据数组中的项目数添加一个新的表头和一个新的表数据,与同一行的索引号匹配.谢谢
控制器:
function Ctrl($scope) {
$scope.data = [];
$scope.data[3] = [];
$scope.data[0] = [['New York', 1000,2000],['Los Angeles', 200,400],['Nottingham', 800,400]]
$scope.moredata = [1500, 2500, 4500];
temp = []
$scope.getData = function() {
$scope.moduleArray[1] = $scope.moredata;
}
$scope.moduleArray = $scope.data;
}
Run Code Online (Sandbox Code Playgroud)
HTML:
<div ng-controller="Ctrl">
<button ng-click="getData()">Get more data</button>
<table>
<tr>
<th>Location</th>
<th>Current Data</th>
<th ng-repeat="ba in moduleArray[1]">new data</th>
</tr>
<tr data-ng-repeat="item2 in moduleArray[0]">
<td>2[0]{{item2[0]}}</td>
<td>2[1]{{item2[1]}}</td>
<td data-ng-repeat="bat in moduleArray[1]">{{bat[$parent.$index]}}</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
这是一个非常简单的设置,可以在右侧切换单个列.
有两组数组,一组用于列标题,另一组用于行数据.它使用limitTo过滤器ng-repeat.
从那里,它是一个简单的增量/减量范围变量colCount来添加/删除列
视图
<button ng-click="increment('up')">Add Column</button>
<button ng-click="increment('down')">Remove Column</button>
<table class="table table-bordered">
<tr>
<th ng-repeat="col in cols | limitTo: colCount">{{col}}</th>
</tr>
<tr ng-repeat="row in data">
<td ng-repeat="item in row | limitTo: colCount">{{item}}</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
调节器
// used as limit for ng-repeat limitTo
$scope.colCount = 3;
$scope.increment = function(dir) {
(dir === 'up') ? $scope.colCount++: $scope.colCount--;
}
$scope.cols = // array of column names
$scope.data = // row data arrays
Run Code Online (Sandbox Code Playgroud)
请注意,对于大型表,由于多个嵌套转发器,这对性能可能不太好