title: Limit checkbox selections and bind to an array in AngularJS
body: <p>I am trying to achieve two things: </p>
  
  <ol>
  <li><p>Bind an array to a list of checkboxes (just a string array), and</p></li>
  <li><p>Limit the number of selections the user can make to a number between
  1 and the number of available items less 1.</p></li>
  </ol>
  
  <p>I can get (2) to work until the user clicks the last item, at which point it loses track and the items remain selected. </p>
  
  <p>The interactive code is up here: <a href="http://codepen.io/adamcodegarden/pen/bdbQqe" rel="nofollow">http://codepen.io/adamcodegarden/pen/bdbQqe</a> (forked from a similar example)</p>
  
  <p>My HTML/Angular code:</p>
  
  <pre><code>&lt;p ng-repeat="item in allOptions" class="item" id="{{item}}"&gt;
        {{item}} &lt;input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" ng-checked="isChecked(item)"&gt; Click this to sync this item with the target array.  {{item}} Selected: {{bool}}
  </code></pre>
  
  <p>and the JS:</p>
  
  <pre><code>var myApp = angular.module("myApp", []);
  
  var maxItems = 1;
  
  myApp.controller('myController', function($scope) {
  
    $scope.isChecked = function(item){
        var match = false;
        for(var i=0 ; i &lt; $scope.data.length; i++) {
          if($scope.data[i] === item) {
            match = true;
          }
        }
        return match;
    };
  
    $scope.allOptions = [
      'one', 'two', 'three', 'four'
    ];
  
    $scope.data = [
    ];
  
    $scope.sync = function(bool, item){
      if (bool) {
        // add item
        $scope.data.push(item);
        // if we have gone over maxItems:
        if ($scope.data.length &gt; maxItems) {
          //remove oldest item
          $scope.data.splice(0,1);
        }
      } else {
        // remove item
        for (var i=0 ; i &lt; $scope.data.length; i++) {
          if ($scope.data[i] === item){
            $scope.data.splice(i,1);
          }
        }      
      }
    };
  
  });
  </code></pre>