您好我想创建一个自定义指令来进行表单验证。我有一个带有复选框和一些文本字段的表单。我想确保用户不会将任何字段留空。
当用户在按下提交后将表单留空时,我希望指令突出显示红色字段的边框。我的问题是,当我创建一个隔离范围指令时它不起作用。如果不是隔离作用域,则只有一个为空时,所有字段都会变为红色。我怎样才能解决这个问题?
指令.js:
directive('createprofileformerrormsg', function() {
return {
scope:{createprofileformerrormsg:'@'},
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
scope.$watch('formErrors', function() {
if (attr.createprofileformerrormsg == 1) {
elem.css("border", "red solid 1px");
}
});
}
}
});
表单.html
<form data-ng-submit="createProfile()">
Ethnicity: <select createprofileformerrormsg="{{formErrors.ethnicity}}" data-ng-
model="ethnicity" >
<option value="Asian">Asian</option>
<option value="Black">Black</option>
<option value="Caucasian">Caucasian</option>
<option value="Hispanic">Hispanic</option>
<option value="Middle Eastern">Middle Eastern</option>
<option value="Native American">Native American</option>
<option value="Other ethnicities">Other ethnicities</option>
</select><br/>
Gender: <select createprofileformerrormsg="formErrors.ethnicity" data-ng-
model="gender">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</form>
控制器.js
$scope.createProfile = function() {
if ($scope.ethnicity == null) {
$scope.formErrors.ethnicity = 1;
error_count++;
}
if ($scope.gender == null) {
$scope.formErrors.ethnicity = 1;
error_count++;
}
}