6
在我的表單驗證中有部分服務器驗證。 所以我應該從服務器列表中返回字段的名稱和每個字段中都有錯誤的字符串。 我的想法是編寫一個通用代碼知識來處理所有領域,而不必事先知道他們,通過訪問他們的名字。 這個領域,例如:如何通過名稱獲取AngularJS元素?
<!-- 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..
}
};
問題是在代碼中的註釋......
我相信訪問正確的價值它只是'$ scope.step1Form.email。$ setValidity' – Fresheyeball
其實你已經在使用這個語法在HTML。究竟是什麼問題? – Fresheyeball
你是對的,如果我想這樣做硬編碼,所以我只需要做$ scope.step1Form.email。$ setValidity,但我的代碼不知道字段名稱(「電子郵件」是動態名稱..它可以是「名字」 ,「lastname」或其他...),所以我需要得到這個元素($ scope.step1Form。+'SomeDynamicVariableName'),然後對它執行setValidity。你讓我? – user3339306