Eric Mitjans
Eric Mitjans

Reputation: 2179

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)?

Upvotes: 1

Views: 39

Answers (1)

random_user_name
random_user_name

Reputation: 26170

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.

From the fiddle, I declared the companydata variable like so:

$scope.companydata = {
  selectedloc: [] // Initialized with an empty array
}

If you want it to be pre-populated, that's simple enough:

$scope.companydata = {
  selectedloc: [0, 1, 2] // Initialized with valu(es) as needed
}

See this updated Fiddle for a richer example where I've updated it with simulated "location" objects.

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

Upvotes: 1

Related Questions