在我的表单验证中,有部分服务器验证。 所以我应该从服务器列表中返回字段名称和每个字符串中包含错误的字符串。 我的想法是通过使用他们的名字访问它们来编写一般代码知识来处理所有字段,而无需事先知道它们。 这是字段,例如:
<!-- Email -->
<div class="form-group" data-ng-class="{ 'has-error' : step1Form.email.$invalid && (!step1Form.email.$pristine || submitted) }">
<label>Email</label>
<input type="email" name="email" class="form-control" data-ng-model="user.email" required data-ng-minlength="5" data-ng-maxlength="60">
<p data-ng-show="step1Form.email.$error.required && (!step1Form.email.$pristine || submitted)" class="help-block">required!</p>
<p data-ng-show="step1Form.email.$error.minlength" class="help-block">too short1</p>
<p data-ng-show="step1Form.email.$error.maxlength" class="help-block">too long!</p>
<p data-ng-show="step1Form.email.$error.email" class="help-block">invalid email!</p>
<p data-ng-show="step1Form.email.$error.serverError" class="help-block">{{emailServerError}}</p>
</div>
就像你可以看到的那样,变量emailServerError被保存用于来自服务器验证的错误... 我的应用程序中有很多字段,我尝试编写适合所有字段的通用代码...
所以这是角度代码:
// function to submit the form after all validation has occurred
$scope.submitForm = function() {
// check to make sure the form is completely valid
if ($scope.step1Form.$valid) {
// now we will go to server side validation
// AJAX calls.......
// lets say we got this back:
var problem = { field: 'email', msg: 'this email is already registered'};
// now we need to setValidity for email input.
var errorVariableName = $parse(problem.field + 'ServerError'); // Get the name of the error string variable.
errorVariableName.assign($scope, problem.msg); // Assigns a value to it
console.log($scope.emailServerError); // = 'this email is already registered'
// HERE THE PROBLEM:
// now i need to do something like that:
// $scope.step1Form. + problem.field + .$setValidity('serverError', false);
// but i dont know how to this that.
// i think that i need to get this element ($scope.step1Form. + problem.field) in some way by name, and then use setValidity on it. but i dont know how..
}
};
问题出在代码内的评论......
答案 0 :(得分:3)
你可以尝试
$scope.step1Form
然后使用
访问正确的值$scope.step1Form["nameOfProblemfield"]