javascript - AngularJS 动态表单字段添加必需属性

标签 javascript html angularjs

我正在尝试验证从后端提供给我的一些表单字段。如果该字段名称需要该属性,我希望能够添加该属性。这是我的 html 端:

      <div class="form-group">

        <!-- ************** ADDITIONAL DYNAMIC FIELDS ******** -->

             <div ng-repeat="field in assetFields" ng-cloak>
                  <div class="col-sm-6">
                     <input type="@{{field.element_type}}" name="@{{field.property}}" class="form-control input-lg" value="" id="@{{field.property}}">
                </div>
      </div>

这是 Angularjs 的一面:

$http.get('/getAssetFeilds/'+$scope.assetType).success(function(data)
            {
                console.log(data);
                $scope.assetFields = data;

                 //loop through the array of json objects
                angular.forEach(data, function(input, key){
                    //get the type of element
                    if(input.element_type == 'text'){
                        //loop through input validations 
                        angular.forEach(input.validations, function(value, key){
                            //check if this input type field is required
                            if(value == 'required'){
                                console.log("#"+input.property);
                                //find the element id value and add required attribute
                                angular.element("#"+input.property).attr('required', 'required');
                            }

                        });
                    }
                });

            });

但是,当我检查元素时,它没有添加属性。这不起作用的原因可能是什么?我认为这会起作用。

最佳答案

属性中“@”的用途是什么?

id="@{{field.property}}"

目前为元素设置的 id 在 id 名称之前有“@”,但是您正在查找 "#"+ input.property 并在其中添加“@”符号,"#@"+ input.property 会给你一个无效错误。

您还需要将 required 属性的添加包装在 $timeout 中,以确保首先呈现 DOM 元素。

$timeout(function() {
    angular.element("#" + input.property).attr('required', 'required');
});

这是一个plnk它的工作原理。

关于javascript - AngularJS 动态表单字段添加必需属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40772821/

相关文章:

javascript - Angular .js : How can I avoid caching services?

javascript - Ajax 成功事件不起作用

html - 我如何在angular4中集成paytm

javascript - AngularJS html 5 模式

javascript - Zepto.js 中的 Dom 异常 12

css - 在页面底部保留页脚 DIV

Jquery 幻灯片奇怪的行为

javascript - Angular ng-Model不同的观点和值(value)

javascript - AngularJS 中的动态表单验证 - 有更好的解决方案/方法吗?

javascript - jquery AjaxSubmit函数如何从表单页面获取结果进行显示