Solving infdig errors caused by filters in ngRepeat can be cumbersome and annoying. When you just want a quick fix, it is often enough to formulate , until the input array changes in order or size, give me the same result .
This is much simpler if the models you deal with all have a unique id property.
In this case, we like to deploy a general approach to filter stabilization:
angular .module( "app" ) .factory( "stabilize", stabilizeFactory ); function stabilizeFactory() { return function stabilize( filterFunc ) { return function stableFilter() { var array = arguments[ 0 ]; if( !array || !array.length ) { return array; } var stabilizationId = idString( array ); if( array.$$stable ) { if( array.$$stableId === stabilizationId ) { return array.$$stable; } } array.$$stable = filterFunc.apply( arguments ); array.$$stableId = stabilizationId; return array.$$stable; }; }; function idString( array ) { return array.reduce( function appendKey( id, element ) { return id + element.id; }, "" ); } }
To use this, simply wrap your own filter function in stabilize() , for example:
angular .module( "app" ) .filter( "myFilter", myFilterProvider); function myFilterProvider( stabilize ) { return stabilize( myFilter); function myFilter( array ) { if( !array || !array.length ) { return array; } return array.filter( function( element ) { return element.something === "foo"; } ); } }
Oliver salzburg
source share