我创建了一个带有一个下拉选择框的一行表格。
我还在表格顶部添加了一个按钮,该按钮复制另一行,该行具有另一个具有相同值的下拉选择框。
存储在选择框中的值是天数。
问题:因为我正在跟踪用户在下拉列表中选择值时所做的更改,所以添加的其他行也将更改为相同的值。例如,如果我选择 3 天的时间段,则其他添加的行也将有 3 天
这是 HTML 代码:
<a class="navbar-brand" ng-click="addRow()" href="#"><button class="btn btn-default"> Add Drug </button></a> <!-- adds rows -->
</div>
</div>
<div class="container-fluid">
<table class="table">
<tr ng-repeat="(rowIndex, row) in rows">
<td>
<!-- Periods dropdown selection box -->
<label>{{row.period}}
<select popover="Choose how many times a day taken" data-ng-model=""period.selectedPeriod""
data-ng-options="name for name in periods" style="width:70px;" required >
</select>
</label>
</td>
<td>
<input type="button" value="-" class="btn btn-primary" ng-click="removeRow(rowIndex)"/>
</td>
</tr>
</table>
在 Controller 内,我为下拉选择框创建了周期值:
//FOR THE DROPDOWN SELECTION BOX
$scope.period = {
currentPeriod: "1 day" //for the data-ng-model
};
$scope.periods = [ //the values
"1 day",
"2 days",
"3 days",
"4 days"
];
以及添加行:
$scope.rows = [
{
'period': "Period"
}
];
$scope.addRow = function() {
$scope.rows.push(angular.copy($scope.rows[0]));
}
我如何尝试解决这个问题?
我认为问题在于data-ng-model
。我的值是 period.selectedPeriod,它会在选择更改时更新。为了解决这个问题,我在 data-ng-model 中输入了一个随机值,下拉选择框不会重复,因为没有跟踪更改。我可以这样做,但是我确实想跟踪用户的选择更改,所以我确实想将 period.selectedPeriod 保留为 data-ng-model 的值
这个问题有解决办法吗?
最佳答案
您的 Controller 需要如下所示,以便在克隆行时还可以重新初始化 selectedPeriod
属性。
然后就可以轻松循环行
并获取已选择的周期。
app = angular.module('app', []);
app.controller('myCtrl', function ($scope) {
$scope.rows = [{
'period': "Period"
}];
$scope.addRow = function () {
var newRow = angular.copy($scope.rows[0]);
newRow.selectedPeriod = null;
$scope.rows.push(newRow);
};
//FOR THE DROPDOWN SELECTION BOX
$scope.period = {
currentPeriod: "1 day" //for the data-ng-model
};
$scope.periods = [ //the values
"1 day",
"2 days",
"3 days",
"4 days"];
$scope.showMeSelectedPeriods = function () {
$scope.rows.forEach(function (value, index) {
console.log(index, value);
});
};
});
关于javascript - 添加行后如何避免下拉重复[AngularJS],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32153301/