KDPV KDPV - 6 months ago 38
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" />
</div>
</form>


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

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

console.log($scope.myForm);
for (var i = 0; i < $scope.models.length; i++) {
console.log($scope.myForm["formElement"+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

I made a plnkr where you will find a solution:

$timeout(function(){
  for (var i = 0; i < $scope.models.length; i++) {
    console.log($scope.myForm["formElement"+i]);
  } 
});

https://plnkr.co/edit/oTttVJrAOiSRn3jfde5q

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.

Comments