【问题标题】:How to make sure that last unchecked checkbox remains checked?如何确保最后一个未选中的复选框保持选中状态?
【发布时间】:2015-12-01 22:20:40
【问题描述】:

我有许多复选框被选中。但是,我希望这样,如果除一个以外的所有其他复选框都未选中,并且您尝试取消选中最后一个选中的复选框,则会出现错误并且不会取消选中该复选框。这是我的尝试:

Checkbox.html:

<input id ="selectDatasource" class="checkboxPosition" type="checkbox" ng-checked="datasourcesSelected.indexOf(datasource.name) > -1 && datasourcesSelected.length > 1" ng-click="toggleSelection(datasource)"> 

Checkbox.js:

$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);
    }
}

现在我显示了警报,但是当我单击它时,最后一个选中的复选框变为未选中状态。我认为因为我的datasourcesSelected 数组没有更新,所以复选框会保持选中状态,但事实并非如此。有什么办法可以让最后一个未选中的复选框保持选中状态?谢谢!

【问题讨论】:

    标签: javascript html angularjs checkbox


    【解决方案1】:

    您是否尝试过使用 ng-change 而不是 ng-click?

    https://docs.angularjs.org/api/ng/directive/ngChange

    再看一遍,你可能需要替换 splice 方法中的 (i) 以使用 $scope.checkboxItem 作为数组中的索引选择器。

    不确定它是否在其他地方使用,但反映当前的 sn-p 代码,$scope.checkboxItem 可能只是一个普通的函数范围变量?

    【讨论】:

    • 您好,您能否详细说明一下您所说的 $scope.checkboxItem 可能只是一个普通的函数范围变量?
    • 另外,checkboxItem 没有在任何地方使用,除了这部分代码:)
    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2016-06-02
    • 2017-08-30
    • 2012-08-25
    相关资源
    最近更新 更多