Remove falsey values when binding in AngularJS
This code snippet removes falsey values when binding an array to an object property in AngularJS.
by Matthew Day
HTML
<div ng-app="myApp">
<div ng-controller="MainCtrl as vm">
<form name="myForm">
<ul>
<li ng-repeat="(key, value) in vm.fruits track by value"><label><input type="checkbox" ng-model="vm.myObject.myArray.value[key]" ng-change="vm.insertIntoArray(value)" ng-true-value="'{{value}}'" />{{value}}</label></li>
</ul>
</form>
<pre>myObject = {{vm.myObject | json}}</pre>
</div>
</div>
CSS
ul {
list-style: none;
}
li {
font-family: 'Arial', sans-serif;
font-size: 12px;
margin: 8px 0;
text-transform: uppercase;
}
JavaScript
angular.module('myApp', []);
angular.module('myApp').controller('MainCtrl', function() {
var vm = this;
vm.myObject = {
myArray: []
}
vm.fruits = ["apple", "orange", "pear", "naartjie"];
vm.insertIntoArray = function(value){
var index = vm.myObject.myArray.indexOf(value);
if(index !== -1) {
vm.myObject.myArray.splice(index, 1);
} else {
vm.myObject.myArray.push(value);
}
};
});
// Thank you to the following for helping me create this snippet:
// http://stackoverflow.com/questions/41170874/ignore-falsey-values-when-binding-an-array-to-an-object-property-in-angularjs
// Answers by Victor Hugo and KreepN
// http://stackoverflow.com/questions/22761340/understanding-the-ngrepeat-track-by-expression
// Question by Jonathan Group
// http://stackoverflow.com/questions/14514461/how-to-bind-to-list-of-checkbox-values-with-angularjs
// Question by nickponline for teaching me a new word in Afrikaans