Skip to content Skip to sidebar Skip to footer

Dynamic Addition Of Div Using Ng-repeat In Angularjs

I am a beginner in angularjs. I want to dynamically add a div while clicking on add icon.I have done some script on this . HTML part:

Solution 1:

You're currently binding all the values to the same object serverinfo, and because you're inside a loop (ng-repeat) then each field in the loop is bound to the same object in the controller.

You have two options:

Bind the fields to the choice element:

<div ng-show="child" class="childDiv" data-ng-repeat="choice in choices track by $index">
    <input  ng-model="choice.childname"type="text" required="required"  placeholder="name"/>
</div>

The above will bind the properties to each choice directly, and will be available in the controller via console.log( $scope.choices[0].childname );

Use the $index indicator to create an array of matched choices:

This is a good solution for cases when you don't want to overwrite/change the values of the original array.

<div ng-show="child" class="childDiv" data-ng-repeat="choice in choices track by $index" ng-init="serverinfo[ $index ].id = choice.id">
    <input  ng-model="serverinfo[ $index ].childname"type="text" required="required"  placeholder="name"/>
</div>

The above will bind the properties to a new array object name serverinfo, where each element is relative to a choice in $scope.choices, it will be available in the controller via console.log( $scope.serverinfo[0].childname );

Note that I also added ng-init="serverinfo[ $index ].id = choice.id" to copy the id property of each choice to the new array elements that are dynamically created by the ngRepeat directive loop.

Solution 2:

using your repeated item name "choice" instead of serverInfo should solve the issue

<divng-show="child"class="childDiv"data-ng-repeat="choice in choices track by $index"><labelfor="childname"class="childname"  >ServerName </label><inputng-model="choice.childname"type="text"required="required"placeholder="name"/><labelfor="childname"class="childname"  >Fullname</label><inputng-model="choice.childfullname"type="text"required="required"placeholder="fullname"/><labelfor="childname"class="childname"  >Mandatory Field</label><inputng-model="choice.field"type="text"required="required"placeholder="city/county.."/><labelfor="childname"class="childname"  >Field values</label><inputng-model="choice.value"type="text"required="required"placeholder=""/><ing-click="removechild()"ng-show="$last"style="padding-left:16em;"class="material-icons">remove</i></div><ing-click="addchild()"style="padding-left:16em;"class="material-icons">add</i>

Solution 3:

That is because you are binding same ng model to each repeating object. put

ng-model="choice.childname"

Do same for other inputs. And if you want serverinfo to contain all this values than copy it.

Post a Comment for "Dynamic Addition Of Div Using Ng-repeat In Angularjs"