我想验证angularjs中的多选。应在多选中至少选择一个项目。如果没有,则不应启用提交按钮。我正在使用 require 来验证表单。我可以通过使用require 强制选择名字,但如何强制选择多选。
表格
<form ng-submit='addStudent()' name='studentForm' novalidate="">
<div class="col-md-4">
<div class="col-md-12">
<label for="Name">First Name *</label>
<input ng-model='student.first_name' name="name" type="text" placeholder="First Name" required class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="col-md-12">
<label for="Name">Last Name </label>
<input ng-model='student.last_name' name="name" type="text" placeholder="Last Name" class="form-control">
</div>
</div>
<multi-selection selectedsubjs="student.selectedSubjects"
allsubjects="allSubjects"
left-title="All Subjects"
right-title="Selected Subjects">
</multi-selection>
<input ng-disabled="sutudentForm.$invalid" type="submit">
</form>
元素指令
app.directive('multiSelection', function(){
return {
restrict: 'E',
scope: {
allsubjects: '=',
selectedsubjs: '=',
displayAttr: '@',
leftTitle: '@',
rightTitle: '@'
},
templateUrl: "templates/multiSelection.html",
link: function(scope) {
scope.swapsubject1 = function(item) {
var index = scope.allsubjects.indexOf(item);
scope.allsubjects.splice(index, 1);
scope.selectedsubjs.push(item);
}
scope.swapsubject2 = function(item) {
var index = scope.selectedsubjs.indexOf(item);
scope.selectedsubjs.splice(index, 1);
scope.allsubjects.push(item);
}
}
};
});
多选模板
<tr>
<td>
<div class="entBox">
<switchitem ng-repeat="subj in allsubjects" value="subj.name" ng-click="swapsubject1(item)" ng-model="allSubjects"></switchitem>
</div>
</td>
<td>
<div class="entBox">
<switchitem ng-repeat="subj in selectedsubjs" value="subj.name" ng-click="swapsubject2(item)" ng-model="student.selectedSubjects"></switchitem>
</div>
</td>
</tr>
答案 0 :(得分:0)
Check this element is not a input type then set
if (!element.isInput()) {
element[0].setCustomValidity(errorMsg);
}