加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何按名称获取AngularJS元素?

发布时间:2020-12-17 07:00:00 所属栏目:安全 来源:网络整理
导读:在我的表单验证中,有一部分服务器验证. 所以我应该从服务器列表中返回字段名称和每个字符串中包含错误的字符串. 我的想法是通过使用他们的名字访问它们来编写一般代码知识来处理所有字段而无需事先知道它们. 这是字段,例如: !-- Email --div class="form-gr
在我的表单验证中,有一部分服务器验证.
所以我应该从服务器列表中返回字段名称和每个字符串中包含错误的字符串.
我的想法是通过使用他们的名字访问它们来编写一般代码知识来处理所有字段而无需事先知道它们.
这是字段,例如:

<!-- 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

然后使用.访问正确的值

$scope.step1Form["nameOfProblemfield"]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读