How to require at least 1 checkbox to validate AngularJS form?

I have an array of JSON objects that displays on the form. I would like to have work on validating the form when the user must select at least one check box for the entire form.

I know that ng-required can be used, but with the implementation I have, this means that all of them must be selected so that they are valid.

Here is the code that I still have:

index.html

 <div ng-repeat="item in volunteerOptions"> <label class="checkbox"><input type="checkbox" value="" data-ng-model="item.selected" ng-required="true">{{ item.content }}</label> </div> <button type="submit" class="btn btn-success" ng-disabled="!memberRegistrationForm.$valid">Submit</button> 

controller.js

 $scope.volunteerOptions = [ { content : 'Content 1', selected : false }, { content : 'Content 2', selected : false }, { content : 'Content 3', selected : false }, { content : 'Content 4', selected : false }, ]; 

Any ideas on how I can achieve this behavior?

+5
source share
1 answer

You can add another scope property and use array.some to check if any of the selected true . Then pass this scope property to ng-required . Sort of

 $scope.isOptionsRequired = function(){ return !$scope.volunteerOptions.some(function(options){ return options.selected; }); } <input type="checkbox" value="" data-ng-model="item.selected" ng-required="isOptionsRequired()"> 
+17
source

Source: https://habr.com/ru/post/1233899/


All Articles