Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 8211  / 10 Years ago, thu, april 24, 2014, 12:00:00

I'm trying to build part of a simple form with Angular yet struggling with a small part of it.



Part of the form has a 'Divisions' section with a list of checkboxes that are dynamically populated from an API call. The user then can select anywhere from 1 to 7 different checkboxes to select which 'Division' the form belongs to.



Then when the user submits the form it should post JSON looking like Divisions: 'div1 div2 div3 div4'



The issue I'm having is for some reason I can't select more than one checkbox at a time. If I try and select another one, it unchecks the first one I selected.



This is the code I'm working with.



        <label>Divisions Participating*</label>
<div class=radio-check-wrap>
<ul class=radio-check-group>
<li ng-repeat=d in divisions>
<input type=checkbox
ng-model=tradeshow.DivisionLead
ng-true-value=div{{$index}}
class= id=div{{$index}}
name=div{{$index}} />
<label for=div{{$index}}>{{d.Description}}</label>
</li>
</ul>
</div>


Also for clarification there is a $scope.divisions = Api.divisions.query(); and a $scope.tradeshow = {} in the controller.



Any idea why I'm unable to select more than one checkbox at a time?


More From » forms

 Answers
1

Your checkboxes are storing the selected value on the same scope object (they all have the same ng-model), so as the check is changed, the ng-model is updated to reflect the newly checked box (which removes the check from the previous).



Here's an answer that shows you the two ways to approach the problem: How do I bind to list of checkbox values with AngularJS?



I made the changes for the object array as input data: http://plnkr.co/edit/otVgVMtwUGkIwr2uaSpq?p=preview



You need to store the selected value on the item, then compute which are selected. So I've changed your checkboxes to this:



<input type=checkbox ng-model=d.selected class= id=div{{$index}} name=selectedDivisions[] />


I've updated your code with methods for getting and storing the selected values:



$scope.divisions = [
{ Description: 'test1' },
{ Description: 'test2' },
{ Description: 'test3' },
{ Description: 'test4' }
];

// selected divisions
$scope.selection = [];

// helper method
$scope.selectedDivisions = function selectedDivisions() {
return filterFilter($scope.divisions, { selected: true });
};

// watch divisions for changes
$scope.$watch('divisions|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (division) {
return division.Description;
});
}, true);

[#45779] Wednesday, April 23, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;