Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add checkbox values to an array in AngularJS?

Someone help me please! Lets say I have an a list of a checkboxes, each checkbox have an ID. I would like to $scope an array with checked checkboxes IDs.

<div ng-app="myapp">
<div ng-controller="ctrlParent">
    <table>           
    <tr ng-repeat="(key, value) in providers">
        <td><input type="checkbox" ng-model="ids[value.Id]">  {{value}} </td>
    </tr>            
    </table>
    {{ids}}
</div>

And my controller:

var app = angular.module('myapp',[]);

app.controller('ctrlParent',function($scope){
    $scope.providers = [{Id:5},{Id:6},{Id:8},{Id:10}];
    $scope.ids = {};
});

Now my array output (if all check boxes are checked) is: {"5":true,"6":true,"8":true,"10":true}

And I would like: [{Id:5},{Id:6},{Id:8},{Id:10}]

like image 236
Djonkwt Avatar asked Dec 25 '22 21:12

Djonkwt


2 Answers

this is a possible solution:

<input type="checkbox" ng-model="ids[$index]" ng-true-value="
        {{value}}" ng-false-value="{{undefined}}"/>{{value}}

In this way, you will have an array of objects, because you are assigning ids[$index] = value.

There is a cons however: when you double check a checkbox, you will have an empty element in the array.

var app = angular.module('myapp', []);

app.controller('ctrlParent', function($scope) {
  $scope.providers = [{
    Id: 5
  }, {
    Id: 6
  }, {
    Id: 8
  }, {
    Id: 10
  }];
  $scope.ids = [];

  $scope.$watchCollection('ids', function(newVal) {
    for (var i = 0; i < newVal.length; ++i) {

      console.log(newVal[i]);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myapp">
  <div ng-controller="ctrlParent">
    <table>
      <tr ng-repeat="(key,value) in providers">
        <td>
          <input type="checkbox" ng-model="ids[$index]" ng-true-value="{{value}}" ng-false-value="{{undefined}}" />{{value}}
        </td>
      </tr>
    </table>{{ids}}</div>
</div>

http://jsfiddle.net/b9jj0re2/3/

like image 154
Michael Avatar answered Jan 07 '23 01:01

Michael


<input type="checkbox" ng-model="ids[$index]" ng-true-value="{{value}}" >

Addign the ng-true-value directive will solve the problem and in controller change the ids from object to array

plunker

like image 32
Neophile Avatar answered Jan 07 '23 01:01

Neophile