Eric Mitjans Eric Mitjans - 4 months ago 24
AngularJS Question

Generating new fields with AngularJS

I'm trying to generate a new form when an item is pushed into an array.
The form is always the same, it just increases by one the conditional count.

Something like this:

<span ng-show="companydata.selectedloc.length == 0">
<div angucomplete-alt id="ex1"
selected-object="selectedLocation"
></div>
</span>

<span ng-show="companydata.selectedloc.length == 1">
<div angucomplete-alt id="ex1"
selected-object="selectedLocation"
></div>
</span>

<span ng-show="companydata.selectedloc.length == 2">
<div angucomplete-alt id="ex1"
selected-object="selectedLocation"
></div>
</span>


Every code block pushes an item into companydata.selectedloc on select (it's an autocomplete select input).

Here's the JS function:

$scope.selectedLocation = function(selected){
$scope.companydata.selectedloc.push(selected)
}


Being always the same code block, is there some way more elegant to do that than increasing the condition manually and adding as many code blocks as necessary (let's say to a max of 10)?

Answer

You should take advantage of Angular's built-in ng-repeat directive.

Here's a working Fiddle

Note that in the fiddle, I added track by $index, since I don't know what your selected values are. Note that track by $index has tradeoffs, but is sometimes required to prevent dupes errors being thrown by Angular.

<span ng-repeat="loc in companydata.selectedloc">
    <div angucomplete-alt id="ex1"
    selected-object="selectedLocation"
    ></div>
</span>