Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
    
Check this out. – Nikos Paraskevopoulos Mar 17 '15 at 11:59
up vote 4 down vote accepted

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/

share|improve this answer
<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

share|improve this answer
1  
Yes, that's exactly what I was looking for. Thank you. – Djonkwt Mar 17 '15 at 12:58
2  
C'mon, it was the same solution I provided, 10 minutes earlier – Michael Mar 17 '15 at 13:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.