Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I had asked a question about How to associate objects as models using ng-options in angularjs.

And I got an awesome answer very fast. My followup questions is that the response uses <select mutiple> to handle the child object array.

You can see a working example of what I want, working with <select> at http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview

How can I use <input type='checkbox'> (instead of <select>) to handle that object array i.e. ng:model="shirt.colors" while repeating the items from colors object array.

The reason, this appears so complicated to me is that I have to manage an array of objects instead of array of values... for example, if you look in the fiddle, there are color objects and shirt object that has multiple colors.

If the color object changes, it should change the corresponding color objects in shirt objects.

Thank you in advance.

share|improve this question

1 Answer 1

up vote 17 down vote accepted

You just need some intermediate value in your scope, and bind checkboxes to it. In your controller - watch for it changes, and manually reconstruct shirt.colors, according to it value.

<div ng-repeat='shirt in shirts'>
  <h3>Shirt.</h3>
  <label>Size: <input ng-model='shirt.size'></label><br/>
  <label>Colors:</label>
  <label ng-repeat="color in colors">
    {{color.label}} <input ng-model="selection[$parent.$index][$index]" type="checkbox"/>
  </label>

    </label>
</div>

And in your controller:

$scope.selection = [[],[]];
$scope.$watch('selection', function () {
  console.log('change', $scope.selection);
  angular.forEach($scope.selection, function (shirtSelection, index) {
    $scope.shirts[index].colors = [];
    angular.forEach(shirtSelection, function (value, index2) {
      if (value) $scope.shirts[index].colors.push($scope.colors[index2]);
    });
  });
}, true);

You can test it here: http://plnkr.co/edit/lh9hTa9wM5fkh3nT09RJ?p=preview

share|improve this answer
    
Thank you. This is exactly what I was looking for :) –  Gunjan Karun Feb 10 '13 at 16:26
    
that's brilliant, thanks a lot! –  alban maillere Jul 23 '14 at 16:55
    
Awesome - Great idea! In addition to using Pythonic's concept, I used this 3rd party directive which helped simplify dealing with Angular's approach to checkboxes. vitalets.github.io/checklist-model –  ClearCloud8 Dec 18 '14 at 23:33

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.