Michael Anthopolous
Michael Anthopolous

Reputation: 231

Adding templates on click

I've got this in my controller:

$scope.myList= [1, 2, 3];

I've got some HTML that looks like this:

<h2>Test Dynamic {{ myList.length }}</h2>
<div ng-repeat="ps in myList">
  <ng-include src="'partials/whatever.html'" >
  </ng-include>
</div>

<span data-ng-click="myList.push(1)">Add</span>

When I click the span, the count in the tag increases, but the list doesn't update. This only needs to be marginally functional; let users add an element with the 'Add' button, and remove one with a remove button in the partial template. Any idea why this isn't working?

Upvotes: 0

Views: 65

Answers (1)

Josep
Josep

Reputation: 13071

The problem is that you are adding a duplicate element and you haven't specified a track by in your ng-repeat function, therefore angular thinks that it's the same element, so you could fix it like this:

<h2>Test Dynamic {{ myList.length }}</h2>
<div ng-repeat="ps in myList track by $index">
  <ng-include src="'partials/whatever.html'" >
  </ng-include>
</div>

<span data-ng-click="myList.push(1)">Add</span>

Upvotes: 3

Related Questions