AngularJS 'ng-filter' is very slow on array of ~1000 elements

后端 未结 6 1769
半阙折子戏
半阙折子戏 2020-12-23 00:11

I have a simple search filter set up for a list of itemnames in AngularJS.

My list looks like this:

var uniqu         


        
6条回答
  •  攒了一身酷
    2020-12-23 00:35

    The main problem with the filter approach is that upon each change the dom is manipulated, so it's not the filter that's slow but the consequences. An alternative is to use something like:

    ng-show="([item] | filter:searchFilter).length > 0"
    

    on the repeated element.

    Lending some code from @OverZealous, you can use the following to compare the behaviour:

    • filter: http://jsbin.com/fuwadanu/1/
    • ng-show: http://jsbin.com/xajehulo/1/

    Update: With Angular v1.2 came the track by syntax. Which also helps with such problems. Provided the elements have some unique attribute, one can use:

    ng-repeat="item in items | filter:searchFilter track by item.id"
    

    Where item.id has to be unique across all items. With track by only those dom-elements will be removed which are no longer the in the final list, others will be remembered. Whereas without track by the whole list is redrawn everytime. In short: much less dom manipulation = quicker redraw.

    • track by: http://jsbin.com/dufasego/1/

提交回复
热议问题