One check to be valid

One box must be check for the form to be valid

by Matthew Day

HTML

<div ng-app="myApp">
  <div ng-controller="MyCtrl as vm">
    <form name="myForm" ng-submit="vm.mySubmit(myForm.$valid)" novalidate>
      <ul>
        <li ng-repeat="fruit in vm.fruits">
        <label><input type="checkbox" ng-model="vm.checked[fruit]" ng-required="!vm.isValidOne(vm.checked)" />{{fruit}}</label>
        </li>
      </ul>
      <div>
        <button type="submit" value="Submit">Submit</button>
      </div>
    </form>
    <hr />
    <pre>{{vm.checked | json}}</pre>
  </div>
</div>

CSS

ul {
  list-style: none;
}

JavaScript

angular.module('myApp', []);

angular.module('myApp')
.controller('MyCtrl', function() {
	var vm = this;
  vm.fruits = [
  	'apples',
    'oranges',
    'pears',
    'peaches'
  ]
  vm.checked = {};
  vm.isValidOne = function(checkObj) {
		return Object.keys(checkObj).some(function(key) {
    console.log(checkObj[key]);
    	return checkObj[key];
    });
  }
  vm.mySubmit = function(data) {
  	if(data == true) {
    	console.log('This form is valid.');
    } else {
    	console.log('This form is invalid.');
    }
  }
});


// Open the console to see whether the form is valid or not.
// Thank you to Klaster_1 at http://stackoverflow.com/questions/19632933/angularjs-group-check-box-validation