在 JSFiddle 中有一个将动态添加的下拉列表。第一个选定的值不应显示在第二个添加的下拉列表中。所以我不会出现重复问题。我怎样才能在AngularJS中实现这个功能。
<select ng-model="personalDetail.fname" ng-repeat="x in names">
</select
$scope.names = ["Emil", "Tobias", "Linus"];
并且我想在下拉值完成时限制动态添加新行。
最佳答案
每个下拉列表都必须根据之前所做的选择来跟踪可用名称
将 $scope.names
声明移至 Controller 顶部
$scope.names = ["Emil", "Tobias", "Linus"];
然后向您的 personalDetail
对象添加一个 names
属性,该属性将用于根据之前的选择来跟踪可用名称
$scope.personalDetails = [
{
'names':$scope.names
}];
现在您可以修改 addNew 函数以在添加下拉列表时设置正确的值数量
$scope.addNew = function(){
$scope.personalDetails.push({
'fname': "",
'lname': "",
'email': "",
// Make a copy of the values set for the previous drop down
'names': $scope.personalDetails[$scope.personalDetails.length - 1].names.slice()
});
// Determine the value of the previous selected name
var previousSelectedName = $scope.personalDetails[$scope.personalDetails.length - 2].fname;
// Get the index of the previous selected name
var index = $scope.personalDetails[$scope.personalDetails.length - 1].names.indexOf(previousSelectedName);
// Remove the name from the valid names list
if(index > -1){
$scope.personalDetails[$scope.personalDetails.length - 1].names.splice(index, 1);
}
}
}
另请记住更新 ng-repeat 以使用您的新名称 individualDetail.names 属性
<tr ng-repeat="personalDetail in personalDetails">
<td>
<select ng-model="personalDetail.fname" ng-options="x for x in personalDetail.names">
</select>
</td>
</tr>
这是新的JSFiddle演示这个
请注意,我没有处理没有可供选择的名称的情况。不过这个案子应该很容易处理。
关于javascript - 如何限制下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48395554/