Marc Rasmussen Marc Rasmussen - 1 month ago 7
AngularJS Question

search.$ also searches for ids

Il jump right to the case.

Basicly when you have an array of objects like this:

{id: 1, name: "Hello", location: "New york", streetNumber: 50}


Then you have an input field:

<input type="text" ng-model="search.$" />


And the following table:

<table>
<thead>
<th>Name</th>
<th>Location</th>
<th>Street number</th>
</thead>
<tr ng-repeat="item in items | filter:search">
<td>
{{item.name}}
</td>
<td>
{{item.location}}
</td>
<td>
{{item.streetNumber}}
</td>
</tr>
</table>


So when you type into the search field: "1".

Then you will also get the object where the
id
matches 1.

My question is how can i exclude items that are not shown?

Fiddle

Answer

Well, take a look at the docs

A special property name ($ by default) can be used (e.g. as in {$: "text"}) to accept a match against any property of the object or its nested object properties.

That's why the results with ids satisfying the criterion get included.

Solution 1, simple but slower working

Add another filtering

<tr ng-repeat="item in items | filter : search | filter : { id: '!search.$' }">


Solution 2, difficult but quick

Consider writing your own filter, e.g.

JS

app.filter('searchFields', function () {
    return function (array, fields, string) {
        fields = fields.split(',');

        var i,
            fieldsLength = fields.length;

        return array.filter(function (item) {
            for (i = 0; i < fieldsLength; i++) {
                if (typeof item[fields[i]] === 'undefined') {
                    continue;
                }

                return (item[fields[i]] + '').indexOf(string) !== -1;
            }
        });
    };
});

HTML

<tr ng-repeat="item in items | searchFields : 'name,location,streetNumber' : search.$">