1

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]
            }
        };

    });

2 Answers 2

2

Checklist Model is the answer

http://vitalets.github.io/checklist-model/

Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.