How to replicate elements dynamically?

Asked

Viewed 2,135 times

5

I’m trying to create a series of repeated elements without knowing the amount of repetitions that will be needed. I have an input in which the user will report a numerical value above or equal to 1 that will reflect on 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 broad) but in this case it is not suitable. Something like this wouldn’t work:

<div ng-repeat="{{ numeroRepeticoes }}">...</div>

2 answers

1

The angular only provides ng-repeat even to iterate over an array defined in $scope. But you can use this to make a mess and iterate over a "symbolic" array. Basically create in $scope a property that will contain the number of desired iterations and then create a function that returns an array of that size. Then you iterate in this 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 there you can use the ng-repeat with this array passing the number of iterations as parameter. That is, if you want to repeat a div it would be

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

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

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

1

This is possible by manually creating an array of items to be displayed by ngRepeat and associating an event ngChange to the field to then regenerate the vector and update 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 type in the field, the function update() will be called, which will change the vector items, which will result in the list being generated according to the number of items.

Demo no jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.