How do I bind to list of checkbox values with AngularJS?
There are two ways to approach this problem. Either use a simple array or an array of objects. Each solution has it pros and cons. Below you'll find one for each case.
With a simple array as input data
The HTML could look like:
<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>
And the appropriate controller code would be:
app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {
// Fruits
$scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];
// Selected fruits
$scope.selection = ['apple', 'pear'];
// Toggle selection for a given fruit by name
$scope.toggleSelection = function toggleSelection(fruitName) {
var idx = $scope.selection.indexOf(fruitName);
// Is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// Is newly selected
else {
$scope.selection.push(fruitName);
}
};
}]);
Pros: Simple data structure and toggling by name is easy to handle
Cons: Add/remove is cumbersome as two lists (the input and selection) have to be managed
With an object array as input data
The HTML could look like:
<label ng-repeat="fruit in fruits">
<!--
- Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
traditionally
- Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
(no two-way-data-binding)
- Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
is arbitrary. The property name could be anything and will be created on the object if not present.
-->
<input
type="checkbox"
name="selectedFruits[]"
value="{{fruit.name}}"
ng-model="fruit.selected"
> {{fruit.name}}
</label>
And the appropriate controller code would be:
app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {
// Fruits
$scope.fruits = [
{ name: 'apple', selected: true },
{ name: 'orange', selected: false },
{ name: 'pear', selected: true },
{ name: 'naartjie', selected: false }
];
// Selected fruits
$scope.selection = [];
// Helper method to get selected fruits
$scope.selectedFruits = function selectedFruits() {
return filterFilter($scope.fruits, { selected: true });
};
// Watch fruits for changes
$scope.$watch('fruits|filter:{selected:true}', function (nv) {
$scope.selection = nv.map(function (fruit) {
return fruit.name;
});
}, true);
}]);
Pros: Add/remove is very easy
Cons: Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method
Demo: http://jsbin.com/ImAqUC/1/
How to bind the model to a list of checkboxes in AngularJS?
Use an ngRepeat
with the key/val syntax:
<div class="form-group">
<input ng-repeat="(day, bool) in vm.reportSchedule.RunOnDays" type="checkbox" name="dailyOption" ng-model="vm.reportSchedule.RunOnDays[day]" />{{day}}
</div>
How to bind single checkbox value with AngularJS Controller
Try this:
$scope.filter = 0;//or 1
HTML:
<input type="checkbox" ng-model="filter" ng-true-value="1" ng-false-value="0">
How to populate list of checkbox values with AngularJS?
I believe you should be using ng-checked instead of ng-model for your radio. Like this:
<input type="radio" id="sin_{{option.questionChoiceValue}}_ques{{option.questionId}}"
ng-checked="question.storedAnswer"
value="{{option.questionChoiceValue | number}}"
name="que_ques{{option.questionId}}"
ng-change="onSelect(question, option);" />
Two way binding in a list of checkbox in angular JS
It seems that you should use ng-model within your checkbox
something like this:
<div class="col-xs-12">
<div class="col-xs-12" ng-repeat="(i, x) in Nodes track by $index" >
<input type="checkbox" style="width:auto" ng-model="Nodes[i].IsActive" ng-checked="x.IsActive"/>
<label style="width:auto">{{x.NodeName}}</label>
</div>`enter code here`
</div>
How to bind a list of checkboxes in AngularJS
i'm not sure what the md-checkbox
directive is so i'm just going to use a normal checkbox input. Generally speaking, setting a default value for inputs in angular involves 2 things:
- Make sure your inputs have
ng-model
to store the value of the checkbox and for 2 way data binding (so that you can set it from the controller as well) - In your controller set the variable declared in the ng-model to whatever default value you want.
So in you html:
<input type="checkbox" class="md-warn md-align-top-left" ng-
model="formationSelection[$index]" ng-true-value="{{formationType}}"
name="formationSelection[]">
Make sure you use ng-true-value to declare the value of each checkbox when checked. The ng-model is set to formationSelection[$index]
which basically means each checkbox is an item inside the formationSelection array, this way the array will be the collection of the values of all checked inputs.
Now $scope.formationSelection = res.candidatureProjetProfessionnel.formations
should work
Here's a working plunker:
http://plnkr.co/edit/sGm39DRWH9EOReiiSrIl?p=preview
Bind all values from array using ng-checked (checkbox) in AngularJS
You can try this:
- in 'is newly selected', you pushed only the employee name.
I changed it to push the whole object of the employee by finding him in the employees array. - in ng-repeat of selected-item, I run all the employees and print its data.
var myApp = angular.module('myApp', []);
myApp.controller('checkBoxController', function ($scope) {
$scope.employees=[{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}];
$scope.selection=[];
// toggle selection for a given employee by name
$scope.toggleSelection = function toggleSelection(employeeName) {
const idx = $scope.selection.findIndex(employee => employee.name === employeeName);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
const employee = $scope.employees.find(employee => employee.name === employeeName);
$scope.selection.push(employee);
}
};
});
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
</head>
<body>
<div class="panel" ng-controller="checkBoxController">
<div class="check-box-panel">
<div ng-repeat="employee in employees">
<div class="action-checkbox">
<input id="{{employee.name}}" type="checkbox" value="{{employee.name}}" ng-checked="selection.indexOf(employee.name) > -1" ng-click="toggleSelection(employee.name)" />
<label for="{{employee.name}}"></label>
{{employee.name}}
</div>
</div>
</div>
<div class="selected-items-panel">
<span class="selected-item">Selected Items:<span>
<div ng-repeat="employee in selection" class="selected-item">
[<span>Name: {{employee.name}} </span>, <span>age: {{employee.age}} </span>]
</div>
</div>
</div>
</body>
</html>
How can I bind list from database into checkbox in AngularJS?
I'll try to help you with assumption that it's not involving ASP.Net controls, just pure HTML controls with Angular
persons
is an array of object: {name: "Mark", id: "00001"}
. In this case any changes to persons
will affect the displayed text inside <li>
tag and vice versa
HTML:
<ul>
<li ng-repeat="person in persons">
<input type="checkbox" ng-model="person.selected" ng-change="onChecked(person)"/>
span {{ person.name }}
</li>
</ul>
Controller(javascript part):
$scope.onChecked = function(selectedPerson){
console.log(selectedPerson.id)
}
Related Topics
How to Check If File Exists in Jquery or Pure JavaScript
How to Deep Clone in JavaScript
How to Determine If a Variable Is 'Undefined' or 'Null'
Why Do You Need to Invoke an Anonymous Function on the Same Line
Get the Real Width and Height of an Image With JavaScript? (In Safari/Chrome)
How to Get Element by Class in JavaScript
Settimeout Calls Function Immediately Instead of After Delay
Changing the Image Source Using Jquery
Find an Element in Dom Based on an Attribute Value
Sum JavaScript Object Propertya Values With the Same Object Propertyb in an Array of Objects
Static Variables in JavaScript
Crockford'S Prototypal Inheritance - Issues With Nested Objects
How to Change Fontsize by JavaScript
Change CSS of Class in JavaScript