KDPV KDPV - 1 year ago 118
AngularJS Question

Angular - access dynamically created form elements from controller

I have a simple form, generated with ng-repeat:

<form name="myForm">
<button ng-click="addFormElement()">+</button>

<div ng-repeat="model in models">
<input type="text" name="formElement{{$index}}" ng-model="model.value" />

New elements are added by clicking the "plus" button. Here is the code:

$scope.addFormElement = function() {
$scope.models.push({ value: "test"});

for (var i = 0; i < $scope.models.length; i++) {

The problem: in the first console log I can see the currently added new input field, but when I try to print the concrete element in the for cycle it logs "undefined". When I add more elements, the last one (currently added) is always defined in first log, but undefined in second. Do you have any idea why?

Printscreen of logs here

Answer Source

I made a plnkr where you will find a solution:

  for (var i = 0; i < $scope.models.length; i++) {


You should call it within a $timeout. You need it for waiting to the next digest cycle of angular. Internally $timeout will call $apply and it will force to synchronize the two way data binding.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download