MatB
MatB

Reputation: 25

nested ng-repeats in angular not updating view

I have some nested controllers each called with ng-repeat.

The bottom level item has the ability to remove itself which it does via a ng-click event. This event splices the item from the array.

In the plunkr below, if you delete the second item (item2), then the array is left with item1 and item3, but the view sees item1 and item2. The sub controllers are never called again and the cached controllers are used.

How can I manually force these controllers to be refreshed? Shouldn't angular do this for me?

http://plnkr.co/edit/jDidC4anikwjZSLMWct6?p=preview

Upvotes: 1

Views: 1432

Answers (2)

Davin Tryon
Davin Tryon

Reputation: 67296

You are currently tracking by $index which will not update the way you want:

Here is an updated plunker.

The only change I made was to take out the track by $index in pitem in items track by $index (toplevel.html):

<div ng-repeat="pitem in items" ng-include="" src="'mid-level.html'" ng-controller="midlevel">test</div>

EDIT:

track by $index will use the $index value as the equality check when deciding what to update in the ng-repeat. So this is what is happening:

  1. After set up we have [i: 0, name: 'item1', i: 1, name: 'item2', i: 2, name: 'item3']
  2. item2 is spliced out
  3. track by $index sees there has been a change and checks if $index with value 0 and 1 still exist in the array
  4. They do, so no update is performed
  5. However $index with value 3 is not there
  6. So, it is updated and removed

Upvotes: 3

Lalit Sachdeva
Lalit Sachdeva

Reputation: 6619

Yes the problem is you are making check on item.name, but you are storing updated list in pitems.name, so if you update your code in mid-level.html from

{{item.name}} <span ng-click="delete(items, $index)">x</span>

to

{{pitem.name}} <span ng-click="delete(items, $index)">x</span>

this is working fine.

Upvotes: 0

Related Questions