Setting up the controller below allows me to add checked values into an array.
(function (app) {
'use strict';
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);
}
};
}]);
})(angular.module('app', []));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="SimpleArrayCtrl">
<div class="row">
<div class="col-md-6">
<h4>selectables</h4>
<form class="form-group" novalidate name="test">
<label ng-repeat="fruitName in fruits" class="checkbox-inline">
<input type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)"> {{fruitName}}
</label>
</form>
</div>
</div>
<div class="row">
<div class="col-md-6">
<h4>selection</h4>
<pre>{{selection|json}}</pre>
</div>
<div class="col-md-6">
<h4>inputs</h4>
<pre>{{fruits|json}}</pre>
</div>
<div class="col-md-6">
<h4>form</h4>
<pre>{{test|json}}</pre>
</div>
</div>
</div>
</div>
I am aiming to bind the array value into the form in order to submit the contents of the array.
Adding ng-model
to my checkbox input only gives me true or false in the array instead of the actual value.
<input ng-model="fruitName" type="checkbox" name="selectedFruits[]" value="{{fruitName}}" ng-checked="selection.indexOf(fruitName) > -1" ng-click="toggleSelection(fruitName)">
Is there a way to bind the value of selection to the model while keeping the checkbox ticked so that I can submit the array value when submitting the form?