title: Angular two-way-binding with sub elements
body: <p>my problem is with creating an angular directive.</p>
  
  <p>I want to create a group of checkboxes with just one single ng-model. It's like a bitfield or flags, i.e. the checkboxes have values from 0, 1, 2, 3 up to n but for ng-model I just want to add 2^value of all checked checkboxes. The values to add are then 1, 2, 4, 8, 16, ...</p>
  
  <p>I wonder if there is a better, more correct or just simpler solution to my problem.</p>
  
  <p><a href="http://plnkr.co/edit/9h7EkEpDohXTniIDHdc5" rel="nofollow">http://plnkr.co/edit/9h7EkEpDohXTniIDHdc5</a></p>
  
  <p>In the example you can change the value in the textbox and the checks will be updated, but not the other way. It's a bit crazy, the code is working on my dev machine, but not in Plnkr!</p>
  
  <pre><code>app.directive('ngCheckboxFlags', function () {
  return {
      restrict: 'A',
      require: 'ngModel',
      link: function (scope, element, attrs, ctrls) {
          var flagSum;
          var checkboxes = [];
  
          // trigger changes of the ngModel
          scope.$watch(attrs.ngModel, function (value) {
              flagSum = value;
              for (var i = 0, ii = checkboxes.length; i &lt; ii; ++i) {
                  var checkbox = checkboxes[i];
                  checkbox.checked = flagSum &amp; (1&lt;&lt;checkbox.value);
              }
          });
  
          for (var i = 0, inputs = element.find('input[type=checkbox]'), ii = inputs.length; i &lt; ii; ++i) 
          {
              var checkbox = inputs[i];
              checkboxes.push(checkbox);
              // trigger changes of HTML elements
              $(checkbox).bind('change', function () {
                  flagSum = ctrls.$viewValue ^ (1&lt;&lt;this.value);
                  console.log(flagSum);
  
                  //ERROR: Change not happening, textbox shows old value
                  scope.$apply(function () {
                      ctrls.$setViewValue(flagSum);
                  });
              });
          }
      }
  };
  });
  </code></pre>
  
  <p>thnx in advance
  knut</p>