4

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

1
  • Check this out. Commented Mar 17, 2015 at 11:59

2 Answers 2

9

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/

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

Comments

1
<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

2 Comments

C'mon, it was the same solution I provided, 10 minutes earlier
down for same solution as above

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.