1

I have an ng-repeat with a filter. When some items are filtered out by the filter and then they are restored after another filter change there are new DOM elements created for these items. If there was any DOM manipulation on the item it gets lost after item is hidden and restored with filter.

Is there a way to keep the DOM elements, even when item is removed by filter?

I tried using track by, but it doesn't help.

Here is a fiddle that recreates the problem. Steps to recreate:

  1. Click the button to apply colors to DOM elements
  2. Type something in the filter input (for example 'ap') to hide some of the elements
  3. Remove the filter. The restored elements lost their style.
TMG
  • 2,620
  • 1
  • 17
  • 40

1 Answers1

2

Angualr is dynamically adding and removing those templates. By template I mean whatever tag(s) are inside your ng-repeat. There is no way to preserve that in an ng-repeat. Instead, if you want this color change to be preserved, it needs to be a part of the model you are ng-repeat ing over. Does that make sense?

Add the color directly to the template style="color: {{fruit.color}}"

See this for what I am talking about

http://jsfiddle.net/nferjvsp/1/

Erik Donohoo
  • 643
  • 3
  • 9
  • Thanks, that makes sense. However I hoped there is a way to work around that. In my real use case the DOM manipulation code is more complex than just setting predefined colour, so it won't be easy to add a relevant model expression in the template. – TMG May 07 '15 at 21:36
  • 1
    @TMG The root of the problem is that you're trying to do this outside of angular. When doing everything within angular, angular will update your DOM for you as needed. If you have complex DOM manipulation code, it sounds like you need a directive to handle this. Then you just stick the directive on these elements, and the DOM will get updated as desired. – dnc253 May 08 '15 at 16:05
  • 1
    @TMG This plunker shows what dnc253 is talking about http://jsfiddle.net/798w3soy/ – Erik Donohoo May 08 '15 at 17:39