【发布时间】:2016-06-13 18:45:42
【问题描述】:
我正在尝试在 Angular.js 中创建一个动态表,用户在提供的文本框中输入列数。然后在 每个 列下提供添加按钮,以添加用户想要的尽可能多的单元格。该单元格只会添加到 that 列。 我正在使用 ng-repeat 来重复列数和 add 按钮。 我能够在变量中获得用户的响应,即用户想要在其下添加单元格的 列。 有人可以给我一个 controller 使用 ng-repeat 、 ng-model 或不使用它来将单元格添加到选定的 column 中。 我的表格代码看起来有点像这样:
<table>
<tr>
<th ng-repeat="n in arr track by $index">SET {{n.setalpha}} </th><!--table heading, dont mind this-->
</tr>
<tr ng-repeat="<!--something goes here-->">
<!--<select ng-model="name" ng-options="options.topicname for options in topics"></select>-->
</tr>
<tr>
<td ng-repeat="n in arr track by $index">
<button ng-click="addSelected($index+1)">add{{$index+1}}</button>
</td>
</tr>
</table>
其中:n in arr track by $index,用于重复表格标题和添加按钮说'n'次,addSelected($index+1)是一个函数,其控制器是:
$scope.addSelected = function (setno) {
console.log(setno);
$scope.thisset = setno;
}
, $scope.thisset 是我有用户响应的变量,即用户想要在其下添加单元格的列。
注意:我只想在用户想要的列中添加单元格。不在所有列中。我的代码:
var app = angular.module('topicSelector', []);
app.controller('topicController', function ($scope) {
$scope.arr = [];
$scope.thisset = -1; //tells in which set, cell has to added.
$scope.topics = [
{
topicid: "1",
topicname: "history"
},
{
topicid: "2",
topicname: "geography"
},
{
topicid: "3",
topicname: "maths"
}
];
$scope.DefineSets = function () {
for (var i = 1; i <= $scope.no_of_sets; i++) {
$scope.arr.push({
setno: i,
setalpha: String.fromCharCode(64 + i)
});
};
};
$scope.addSelected = function (setno) {
console.log(setno);
$scope.thisset = setno;
}
});
table {
width: 100%;
}
<!doctype html>
<html ng-app="topicSelector">
<head>
<title>
topic selector
</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h3>Enter number of sets:</h3>
<div ng-controller="topicController">
<form ng-submit="DefineSets()">
<input type="text" ng-model="no_of_sets" placeholder="number of sets" name="no_of_sets">
<button>Submit</button>
</form>
<br>
<br>
<table>
<tr>
<th ng-repeat="n in arr track by $index">SET {{n.setalpha}} </th>
</tr>
<!--<tr ng-repeat="">
<select ng-model="name" ng-options="options.topicname for options in topics"></select>
</tr>-->
<tr>
<td ng-repeat="n in arr track by $index">
<button ng-click="addSelected($index+1)">add{{$index+1}}</button>
</td>
</tr>
</table>
</div>
</body>
</html>
链接到 PLUNK PLUNK
【问题讨论】:
-
请使用您的代码创建一个 plunker。这将帮助我们帮助您。
-
你用的是什么版本的angularjs?
-
Angular 1,版本 1.5.6
-
@jbrown 我已添加链接
-
恕我直言,表格不是解决您问题的最佳元素。如果您对此没有任何限制,使用列表实现的水平和垂直弹性框组合应该会更好。
标签: angularjs