Search code examples
javascriptangularjsarraysangularjs-ng-repeatangular-ngmodel

Add an array by selecting checkbox with ng-repeat


I faced with a small problem adding proper data to my submit form. All fileds for this form come dynamically from http request, one of this fields is categories, values for this field come dynamically from another http request, with help of ng-repeat I render values in my form. Values have an ids and names. I need to send in my form the array of ids of categories looks like categories: [1,4,5,7], where numbers are id of selected categories. The problem is my array looks like categories: [1: true, 5, true ] what is totally wrong. This is plunker with my problem. I suppose something wrong with my ng-model, but cannot find what exactly. So could anybody tell me what I am missing?

code

     $scope.category = [
    {"id":5,"name":"Data Quality"},
    {"id":2,"name":"Documentation"},
    {"id":4,"name":"Drug Supply"},
    {"id":8,"name":"Enrollment"},
    {"id":3,"name":"Patient Safety"},
    {"id":7,"name":"Randomization"},
    {"id":9,"name":"Site Performance"},
    {"id":1,"name":"Study Conduct"},
    {"id":6,"name":"Technology Related"}
    ]

    $scope.sendData = {}

    $scope.vmodel = angular.copy($scope.sendData);

 $scope.onSubmit = function (event) {
                if (event.id == null || event.id == 0) {
                    console.log(event)
                }
            };

html

 <div class="form-check-inline" ng-repeat="cat in category">
      <label class="form-check-label col-xs-4 no-padding" for="categories" ng-true-value="'{{cat.name}}'" ng-false-value="''">
                        {{ cat.name }}
                  <input type="checkbox" 
                  class="form-check-input col-xs-2"
                  id="categories" 
                  ng-model="vmodel.categories[cat.id]" />
      </label>
    </div>

Solution

  • <label class="form-check-label col-xs-4 no-padding" for="categories" ng-true-value="'{{cat.name}}'" ng-false-value="''">
                {{ cat.name }}
                <input type="checkbox" class="form-check-input col-xs-2"  ng-click="add(cat.id)" id="categories" />
              </label>
    
    
    $scope.sendData = {
        categories: []
      }
    
      $scope.add = function(id) {
        if ($scope.sendData['categories'].indexOf(id) == -1) {
          $scope.sendData.categories.push(id);
        } else {
          $scope.sendData.categories.splice($scope.sendData['categories'].indexOf(id), 1);
    
        }
        console.log($scope.sendData);
    
    
    
      }
    
      $scope.onSubmit = function(event) {
    
        console.log($scope.sendData)
      };