Checked Values to Array
AngularJS app that adds or removes checked values to an array.
HTML
<div ng-app="myApp">
<ul ng-controller="SomeCtrl as data">
<li ng-repeat="fruit in data.fruits">
<label><input type='checkbox' ng-checked="fruit.checkedFruits.indexOf(fruit) != null" ng-click="data.toggleCheck(fruit)" /> {{fruit}}</label>
</li>
<div>
<pre>Checked Fruits Array: {{data.checkedFruits}}</pre>
</div>
</ul>
</div>
CSS
ul {
list-style: none;
}
JavaScript
// See notes below
angular.module('myApp', []);
angular.module('myApp').controller('SomeCtrl', function() {
var vm = this;
vm.fruits = ["apple", "orange", "pear", "naartjie"];
vm.checkedFruits = [];
vm.toggleCheck = function (fruit) {
if (vm.checkedFruits.indexOf(fruit) === -1) {
vm.checkedFruits.push(fruit);
} else {
vm.checkedFruits.splice(vm.checkedFruits.indexOf(fruit), 1);
}
};
});
// NOTES
// This fiddle is based on a StackOverflow answer given by Umur Kontaci at http://stackoverflow.com/questions/14514461/how-to-bind-to-list-of-checkbox-values-with-angularjs accessed on December 14, 2016.
// This code uses Controller As syntax whereas Umur's code uses $scope.