I am using Angular 1.4.8 and would like to put only the checked values of a list into an array. This array then needs to be the value of an object property, like this:
myObject = {
"myArray": [
"apple",
"orange",
"pear"
]
}
My HTML:
<div ng-app="myApp">
<div ng-controller="MainCtrl as vm">
<form name="myForm">
<ul>
<li ng-repeat="fruit in vm.fruits track by $index">
<label>
<input type="checkbox" ng-model="vm.myObject.myArray[$index]" ng-true-value="'{{fruit}}'" ng-false-value="undefined" />{{fruit}}
</label>
</li>
</ul>
</form>
<pre>myObject = {{vm.myObject | json}}</pre>
</div>
</div>
My JS:
angular.module('myApp', []);
angular.module('myApp').controller('MainCtrl', function() {
var vm = this;
vm.myObject = {
myArray: []
}
vm.fruits = ["apple", "orange", "pear", "naartjie"];
});
For easy reference, see this fiddle.
Note that when you check and then uncheck a list item, the array retains a value of null. I do not want null bound to the array because it adds to its length and this is causing issues with other code.
How can I ignore binding falsey values like null, undefined, etc...?