1

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

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Also why using the syntacs ng-include="" src="'mid-level.html'" when you can use directly ng-include"'mid-level.html'"
Thanks very much!!! Is there any documentation about why the track by is not working as I expect?
@MatB I have added a detailed breakdown of how using $index is breaking the expected behaviour.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.