Javascript 如何确保最后一个未选中的复选框保持选中状态?
我有很多复选框,都被选中了。但是,我希望这样,如果除一个复选框外所有其他复选框都未选中,并且您尝试取消选中最后选中的复选框,则会出现错误,并且该复选框不会被取消选中。这是我的尝试: Checkbox.html:Javascript 如何确保最后一个未选中的复选框保持选中状态?,javascript,html,angularjs,checkbox,Javascript,Html,Angularjs,Checkbox,我有很多复选框,都被选中了。但是,我希望这样,如果除一个复选框外所有其他复选框都未选中,并且您尝试取消选中最后选中的复选框,则会出现错误,并且该复选框不会被取消选中。这是我的尝试: Checkbox.html: <input id ="selectDatasource" class="checkboxPosition" type="checkbox" ng-checked="datasourcesSelected.indexOf(datasource.name) > -1 &
<input id ="selectDatasource" class="checkboxPosition" type="checkbox" ng-checked="datasourcesSelected.indexOf(datasource.name) > -1 && datasourcesSelected.length > 1" ng-click="toggleSelection(datasource)">
现在我已经显示了警报,但当我单击最后一个选中的复选框时,它将变为未选中。我认为,因为我的
datasourceselected
数组没有更新,所以复选框将保持选中状态,但事实并非如此。是否有任何方法可以使最后一个未选中的复选框保持选中状态?谢谢 您是否尝试过使用ng change而不是ng click
再次查看,您可能需要替换splice方法中的(i),以使用$scope.checkboxItem作为数组中的索引选择器
不确定它是否在其他地方使用,但反映了当前的代码片段,$scope.checkboxItem可能只是一个普通函数范围变量?您好,您能详细说明一下$scope.checkboxItem可能只是一个普通函数范围变量的含义吗?此外,除了这部分代码之外,checkboxItem在其他地方都没有使用:)
$scope.datasourcesSelected = ['a', 'b', 'c']
//Listen for checked datasources
$scope.toggleSelection = function(datasource){
if($scope.datasourcesSelected.length === 1){
alert('Error!')
//Make sure that checkbox is not unchecked.
return;
}
$scope.checkboxItem = $scope.datasourcesSelected.indexOf(datasource.name);
//Currently selected within selected
if($scope.checkboxItem > -1){
$scope.datasourcesSelected.splice(i, 1);
}
else{
$scope.datasourcesSelected.push(datasource.name);
}
}