ballerz ballerz - 4 months ago 31
AngularJS Question

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="@{{}}" class="form-control input-lg" value="" id="@{{}}">

Here is Angularjs side of it:

$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'){
//find the element id value and add required attribute
angular.element("#"'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.


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


Currently the id being set for the elements has the '@' preceding the id name however you are looking for "#" + and adding the '@' symbol there, "#@" + 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("#" +'required', 'required');

Here is a plnk of it working.