mardi 1 décembre 2015

How to make sure that last unchecked checkbox remains checked?

I have a number of checkboxes that come checked. However, I want it so that if all other checkboxes are unchecked except one, and you try to uncheck that last checked checkbox, an error will come up and that checkbox will not be unchecked. This was my attempt:

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

Right now I have the alert showing but the last checked checkbox becomes unchecked when I click on it. I thought that because my datasourcesSelected array is not updated, the checkbox would stay checked but that's not the case. Is there any way that I can keep force the last unchecked checkbox to remain checked? Thanks!




Aucun commentaire:

Enregistrer un commentaire