ballerz
ballerz

Reputation: 487

AngularJS dynamic form field with adding required attribute

I am trying to validate some form fields which are given to me from a backend. I want to be able to add the required attribute if that field name needs that attribute. Here is what I have html side:

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

Here is Angularjs side of it:

$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');
                            }

                        });
                    }
                });

            });

However,its not adding the attribute when I do inspect element. what could be the reason for this not working? which I thought would have worked.

Upvotes: 0

Views: 2138

Answers (1)

machinehead115
machinehead115

Reputation: 1657

What is the purpose of the '@' in the attributes?

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

Currently the id being set for the elements has the '@' preceding the id name however you are looking for "#" + input.property and adding the '@' symbol there, "#@" + input.property will give you an invalid error.

You will also need to wrap the adding of the required attribute in a $timeout to make sure the DOM element is rendered first.

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

Here is a plnk of it working.

Upvotes: 1

Related Questions