user567
user567

Reputation: 3862

Select only two checkbox

I have a checkbox list and I want that the user be able to select just two of them and I want to get the value of the selected ones. I tried this code HTML

<input type="checkbox" value={{item.name}} id={{item.name}} ng-click="toggleSelection(item.name)">

JS

$scope.toggleSelection = function toggleSelection(id) {
    if(typeof $scope.firstSelectedService === 'undefined'){
    $scope.firstSelectedService=id;
    }
    else
    if(typeof $scope.secondSelectedService === 'undefined'){
    $scope.secondSelectedService=id;
    }
    else
    if($scope.firstSelectedService === id){
    window.alert("test11");
    $scope.firstSelectedService='';
    }
    else
    if($scope.secondSelectedService === id){
    window.alert("test2");
    $scope.secondSelectedService='';
    }
};

if the user select a third one I want to delete the old value of secondSelectedService and if he de-select a checked one, I want to delete it's value. I have a trouble when deselecting one, I don't see the alert box with "test1" or "test2", I see it only if I select the checkbox again. I only want to ask if it's a good way to do it like this ? it don't really looks clean.

Upvotes: 1

Views: 182

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136164

Your ng-click directive should not contain {{}} interpolation directive, also you should have ng-model on the checkbox so that the value of item will updated, there is not need to call toggleSelection either

Markup

<div ng-repeat="item in items">
    <input type="checkbox" ng-value="item.value" id="{{item.name}}"
     ng-click="item.selected!=item.selected" ng-model="item.selected"/>
</div>

Then if you want how many items are selected, for that you could use filter like {{(items|filter: {selected: true}: true)}} this will give you the items which are selected on html

Markup

<body class="container" ng-app="firstApp" ng-controller="EmpController">
  <div ng-repeat="item in items">
    <input type="checkbox" ng-value="item.value" id="{{item.name}}" 
     ng-click="item.selected!=item.selected" ng-model="item.selected" />
       {{item.name}}
  </div>
  {{items|filter:{selected: true}: true}}
</body>

Plunkr Demo

OR

If you wanted use those selected element in controller then you could use $filter object inside controller, like $filter('filter')($scope.items, {selected: true}, true)

Upvotes: 1

KoIIIeY
KoIIIeY

Reputation: 558

$scope.variables = [];
$scope.toggleSelection = function toggleSelection(id) {
    if($scope.variables.length >= 2){
        $scope.variables[0] = $scope.variables[1];
        $scope.variables[1] = id;
    } else {
        $scope.variables.push(id);
    }
}

Upvotes: 1

Related Questions