简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM