簡體   English   中英

AngularJS動態表單字段,添加了必需的屬性

[英]AngularJS dynamic form field with adding required attribute

我正在嘗試驗證從后端提供給我的一些表單字段。 如果該字段名稱需要該屬性,我希望能夠添加該屬性。 這是我有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添加“ @”符號, "#@" + input.property將為您提供invalid錯誤。

您還需要將required屬性的添加包裝在$timeout ,以確保首先呈現DOM元素。

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

這里是一個plnk的正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM