Add filters in ng-init

IOR88 picture IOR88 · Feb 11, 2015 · Viewed 8.2k times · Source
<input ng-model="search.name" placeholder="Name" />

<tbody>
<div ng-init="FilteredGeojson = ho|filter:search">
<tr ng-repeat="hf in FilteredGeojson">
    <td>{{ hf.name }}</td>   
</tr>
</div>
</tbody>
</table>
<div leaflet-directive id="map" data="FilteredGeojson"></div>

It is important to do filtering in ng-init if it is possible, but i cannot solve it, i cannot make ng-repeat and create scope which i pass after to my directive cause it start infinite digest loop.

Answer

Sharikov Vladislav picture Sharikov Vladislav · Feb 11, 2015

The answer to your question

Your snippet doesn't work because of ho and filter:search are different statements. In

ng-init="FilteredGeojson = ho | filter:search"

... the assignment FilteredGeojson = ho is done before the filter | filter:search is applied, which does not work.

You need to encapsulate filtering the value like this:

ng-init="FilteredGeojson = (ho | filter:search)"

Also

It is important to do filtering in ng-init

Important for what? ngInit directive will be called only once there, so when you'll update your filter, items in ngRepeat wouldn't be updated. But you need this, right?

To achieve this you should add filter in ngRepeat directive, like this:

<tr ng-repeat="hf in FilteredGeojson | filter:search">
    <td>{{ hf.name }}</td>   
</tr>

Example

Both solutions are available in this plnkr example.