我有一个复选框列表,其中至少一个是强制性的。我试图通过AngularJS验证来实现这一点,但是很难。下面是我的代码:
// Code goes here for js var app = angular.module('App', []); function Ctrl($scope) { $scope.formData = {}; $scope.formData.selectedGender = ''; $scope.gender = [{ 'name': 'Male', 'id': 1 }, { 'name': 'Female', 'id': 2 }]; $scope.formData.selectedFruits = {}; $scope.fruits = [{ 'name': 'Apple', 'id': 1 }, { 'name': 'Orange', 'id': 2 }, { 'name': 'Banana', 'id': 3 }, { 'name': 'Mango', 'id': 4 }, ]; $scope.submitForm = function() { } } // Code goes here for html <!doctype html> <html ng-app="App"> <head> <!-- css file --> <!--App file --> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script> <!-- External file --> </head> <body> <div ng-controller="Ctrl"> <form class="Scroller-Container"> <div ng-app> <form class="Scroller-Container" ng-submit="submit()" ng-controller="Ctrl"> <div> What would you like? <div ng-repeat="(key, val) in fruits"> <input type="checkbox" ng-model="formData.selectedFruits[val.id]" name="group[]" id="group[{{val.id}}]" required />{{val.name}} </div> <br /> <div ng-repeat="(key, val) in gender"> <input type="radio" ng-model="$parent.formData.selectedGender" name="formData.selectedGender" id="{{val.id}}" value="{{val.id}}" required />{{val.name}} </div> <br /> </div> <pre>{{formData.selectedFruits}}</pre> <input type="submit" id="submit" value="Submit" /> </form> </div> <br> </form> </div> </body> </html>
以下是plunker中的代码:http ://plnkr.co/edit/Bz9yhSoPYUNzFDpfASwt?p=preview 有没有人在AngularJS上做到这一点?使复选框成为必需,迫使我选择所有复选框值。AngularJS文档中也未记录此问题。
如果要选择组中的至少一项,则可以使用 ng-required* 定义动态的 required 属性。 *
对于性别单选按钮,这很容易:
<input type="radio" ng-model="formData.selectedGender" value="{{val.id}}" ng-required="!formData.selectedGender" >
如果使用数组存储选定的水果(只需检查数组长度),复选框组也将很容易,但是对于对象,有必要检查是否使用控制器中的过滤器或函数将任何值设置为true:
$scope.someSelected = function (object) { return Object.keys(object).some(function (key) { return object[key]; }); } <input type="checkbox" value="{{val.id}}" ng-model="formData.selectedFruits[val.id]" ng-required="!someSelected(formData.selectedFruits)" >
更新:
const someSelected = (object = {}) => Object.keys(object).some(key => object[key])
另外请记住,如果value为0,它将返回false。