gpt4 book ai didi

angularjs - 如何按名称获取 AngularJS 元素?

转载 作者:行者123 更新时间:2023-12-04 15:34:21 24 4
gpt4 key购买 nike

在我的表单验证中有一部分服务器验证。
所以我应该从服务器列表中返回包含字段名称和每个字段中包含错误的字符串。
我的想法是编写一个通用的代码知识来处理所有字段,而无需事先知道它们,通过使用它们的名称访问它们。
这是字段,例如:

<!-- 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 被保存为来自服务器验证的错误......
我的应用程序中有很多领域,我尝试编写适合所有领域的通用代码......

所以这是 Angular 代码:
// 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

然后访问正确的值
$scope.step1Form["nameOfProblemfield"]

关于angularjs - 如何按名称获取 AngularJS 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21947518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com