I have a few checkboxes:
There is a way to work on the array directly and use ng-model at the same time through ng-model-options="{ getterSetter: true }"
.
The trick is to use a getter/setter function in your ng-model. This way you can use an array as your real model and "fake" the booleans in the input's model:
$scope.fruits = ['apple', 'pear']; // pre checked
$scope.fruitsGetterSetterGenerator = function(fruitName){
return function myGetterSetter(nowHasFruit){
if (nowHasFruit !== undefined){
// Setter
fruitIndex = $scope.fruits.indexOf(fruit);
didHaveFruit = (fruitIndex !== -1);
mustAdd = (!didHaveFruit && nowHasFruit);
mustDel = (didHaveFruit && !nowHasFruit);
if (mustAdd){
$scope.fruits.push(fruit);
}
if (mustDel){
$scope.fruits.splice(fruitIndex, 1);
}
}
else {
// Getter
return $scope.user.fruits.indexOf(fruit) !== -1;
}
}
}
CAVEAT You shouldn't use this method if your arrays are big as myGetterSetter
will be called a lot of times.
For more on that, see https://docs.angularjs.org/api/ng/directive/ngModelOptions.