Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
3 views
in Web Technology by (47.6k points)

I have a few checkboxes:

<input type='checkbox' value="apple" checked>

<input type='checkbox' value="orange">

<input type='checkbox' value="pear" checked>

<input type='checkbox' value="naartjie">

That I would like to bind to a list in my controller such that whenever a checkbox is changed the controller maintains a list of all the checked values, for example, ['apple', 'pear'].

ng-model seems to only be able to bind the value of one single checkbox to a variable in the controller.

Is there another way to do it so that I can bind the four checkboxes to a list in the controller?

2 Answers

+2 votes
by (106k points)
edited by

You can bind to a list of checkbox values with AngularJS with a simple array as input data. 

Looking for Angularjs material from basics! Refer to this video on Angularjs provided by Intellipaat:

See the code below:-

<label ng-repeat="fruitName in fruits">

<input

type="checkbox"

name="selectedFruits[]"

value="{{fruitName}}"

ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)" >

{{fruitName}}

</label>

0 votes
by (180 points)
edited by

A simple solution:

<div ng-controller="MainCtrl">
<label ng-repeat="(color,enabled) in colors">
<input type="checkbox" ng-model="colors[color]" /> {{color}}
</label>
<p>colors: {{colors}}</p>
</div>

<script>
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope){
$scope.colors = {Blue: true, Orange: true};
});
</script>

Full Source With Example At Icetutor.com

Related questions

+2 votes
1 answer
0 votes
1 answer
+2 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...