title: Bind Checkboxes to Angular Model array
body: <p>I want to bind a list of checkboxes to an array directly in angular, so that when the checkbox is selected, it's value is pushed onto the array, and when not checked, it is popped off, so that the array on the model always represents the final state I want. Previously, I had done it by mapping checkboxes to array index, and then later stripping out <code>null</code> values - but I would like to try it another way.</p>
  
  <p>I want stop binding directly to the model, but just run a function when the checkboxes are updated, which handles putting data on the array.</p>
  
  <ol>
  <li>Is there anything wrong with this approach?</li>
  <li>Are there any caveats I must beware of when updating the model from the controller?</li>
  </ol>
  
  <p>HTML (Angular)</p>
  
  <pre><code>&lt;div ng-app="app" ng-controller="Ctrl"&gt;
      &lt;span ng-repeat='option in options'&gt;
          &lt;label&gt;{{option.value}}&lt;/label&gt;
          &lt;input type="checkbox"         
          ng-value="option.code"
       ng-checked="selected.indexOf(option.code) &gt; -1"
          ng-click="toggleSelect(option.code)" /&gt;
          &lt;br /&gt;
      &lt;/span&gt;&lt;br /&gt;
      {{selected}}
  &lt;/div&gt;
  </code></pre>
  
  <p>JavaScript (Angular)</p>
  
  <pre><code>var App = angular.module('app', []);
  
  App.controller('Ctrl', ['$scope', function($scope){
      $scope.options = [
          {value: "Jan", code: 1}, 
          {value: "Feb", code: 2}, 
          {value: "Mar", code:  3}, 
          {value: "Apr", code:  4}, 
          {value: "May", code:  5}, 
          {value: "Jun", code:  6}, 
          {value: "Jul", code:  7}, 
          {value: "Aug", code:  8}, 
          {value: "Sep", code:  9}, 
          {value: "Oct", code:  10}, 
          {value: "Nov", code:  11}, 
          {value: "Dec", code:  12}
      ];
  
      $scope.selected = [1, 2, 9]
  
      $scope.toggleSelect = function toggleSelect(code) {
          var index = $scope.selected.indexOf(code)
  
          if (index == -1) {
              $scope.selected.push(code)
          }
          else {
              $scope.selected.splice(index, 1)
          }
      }
  }]);
  </code></pre>
  
  <h2>Demo: <a href="http://jsfiddle.net/rianodwyer/8dPRn/" rel="nofollow">http://jsfiddle.net/rianodwyer/8dPRn/</a></h2>