How to replicate elements dynamically?

5

I'm trying to create a series of repeating elements without knowing the amount of repetitions that will be needed. I have an input in which the user will report a numerical value equal to or greater than 1 that will reflect the amount of repetitions required.

<input type="text" ng-model="numeroRepeticoes">

The only repeat command I know is ng-repeat (my knowledge in Angular is not very wide) but in this case it is not apt. Something like this would not work:

<div ng-repeat="{{ numeroRepeticoes }}">...</div>
    
asked by anonymous 05.05.2014 / 20:56

2 answers

1

Angle only provides ng-repeat even to iterate over an array defined in $scope . But you can use this to do a crap and iterate over a "symbolic" array. Basically create in $scope a property that will contain the number of iterations you want, and then create a function that returns an array of that size. So you iterate in that array.

In code, you would have

// Número inicial de iterações
$scope.numIteracoes = 1;

// Construção do array 'fake'
$scope.iterador = function (num) {
    return new Array(num);
}

From here you can use ng-repeat with this array by passing the number of iterations as a parameter. That is, if you want to repeat a div would be

<div ng-repeat="num in iterador(numIteracoes) track by $index">
    <!-- códigos da div aqui -->
</div>

Note that since numIteracoes is a property of $scope you can update it dynamically, for example with input with ng-model pointing to it.

This track by $index is for you to identify the items by the position in the array. You can see more about this syntax here .

    
05.05.2014 / 22:08
1

This is possible by manually creating an array of items to be displayed by ngRepeat and associating a event ngChange to the field to then regenerate the vector and refresh the list.

Consider the following template:

<input type="text" ng-model="numeroRepeticoes" ng-change="update()"/><br/>
Itens:
<div ng-repeat="item in items">Item {{ item }} ({{ $index }})</div>

And the following code:

var loopApp = angular.module('loopApp', []);
loopApp.controller('LoopCtrl', function ($scope) {
    $scope.update = function() {
        $scope.items = [];
        var total = parseInt($scope.numeroRepeticoes);
        for (var i = 0; i < total; i++) {
            $scope.items.push(i + 1);
        }
    };
});

Then, each time the user types in the field, the update() function will be called, which will change the items vector, which will result in the list being generated according to the number of items.

Demo on jsfiddle

    
05.05.2014 / 22:14