1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.