簡體   English   中英

如何確保最后一個未選中的復選框保持選中狀態?

[英]How to make sure that last unchecked checkbox remains checked?

我選中了許多復選框。 但是,我想要這樣,如果所有其他復選框都未選中,而您嘗試取消選中最后選中的復選框,則會出現錯誤,並且不會取消選中該復選框。 這是我的嘗試:

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數組未更新,所以該復選框將保持選中狀態,但事實並非如此。 有什么方法可以讓我強制最后一個未選中的復選框保持選中狀態? 謝謝!

您是否嘗試過使用ng-change而不是ng-click?

https://docs.angularjs.org/api/ng/directive/ng更改

再次查看,您可能需要在splice方法中替換(i)才能使用$ scope.checkboxItem作為數組中的索引選擇器。

不確定是否在其他地方使用了它,但反映了當前的代碼片段,$ scope.checkboxItem可能只是一個普通的函數范圍變量?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM