Reputation: 7340
My HTML is
<label>
<input type="checkbox" name="Communities" ng-model="formData.User.Communities" value="1" id="YOURROLE_0">
COACH</label>
<br>
<label>
<input type="checkbox" name="Communities" ng-model="formData.User.Communities" value="2" id="YOURROLE_1">
ATHLETE</label>
<br>
<label>
<input type="checkbox" name="Communities" ng-model="formData.User.Communities" value="3" id="YOURROLE_2">
PARENT</label>
How can I specify the HTML/Javascript that I get the model as below. I need the checkboxes (checked ones) as an array populated to the array.
.controller('formController', function($scope) {
$scope.formData = {
"User": {
"Communities": [1, 2, 3]
}
};
});
Upvotes: 1
Views: 470
Reputation: 57435
Here's an approach without a third-party library, similar to AngularJS: How to bind selected checkbox items to empty array:
angular.module("exampleApp", [])
.controller("formController", function($scope) {
$scope.communities = [
{
name: "COACH",
value: 1,
checked: false,
},
{
name: "ATHLETE",
value: 2,
checked: false,
},
{
name: "PARENT",
value: 3,
checked: false,
},
];
$scope.formData = {
User: {
Communities: []
}
};
$scope.updateSelected = () => {
$scope.formData.User.Communities = $scope.communities
.filter(e => e.checked)
.map(e => e.value);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
<div ng-app="exampleApp">
<div ng-controller="formController">
<div ng-repeat="community in communities">
<label>
<input
type="checkbox"
ng-model="community.checked"
ng-change="updateSelected()"
id="YOURROLE_{{$index}}"
>
{{community.name}}
</label>
</div>
<div ng-repeat="selected in formData.User.Communities">
{{selected}}
</div>
</div>
</div>
See also: How do I bind to list of checkbox values with AngularJS?
Upvotes: 0
Reputation: 7340
Checklist Model is the answer
http://vitalets.github.io/checklist-model/
Upvotes: 2