ak85 ak85 - 6 months ago 20
AngularJS Question

filter results to show matching results with ng-show angular js

I can filter results with the below where all entries appear on the page

<body ng-app="">
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>

Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</body>


What I am trying to achieve is a jquery UI autocomplete type solution where there is nothing on the page initially but as you type the matching entries appear.

I thought I might be able to do this with ng-show, so far I can only do for example

ng-show="searchText == 'John'"


which means it will always be blank unless you type in John.
Is there a way with ng-show or ng-if to filter (show matching entries) as you type like the filter does?
I have the below demonstrating my John example

<body ng-app="">
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>

Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText" ng-show="searchText == 'John'">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</body>


I also tried

ng-show="searchText == searchText"


but this just shows all items?
Can this be done with ng-show?
Is there a better way?

Answer

You want to create a custom filter. It can be done very easily. This filter will test the name of your friend against the search. If

app.filter('filterFriends', function() {
    return function(friends, search) {
        if (search === "") return friends;
        return friends.filter(function(friend) {
           return friend.name.match(search); 
        });
    }
});

This should give you a good idea of how to create filters, and you can customize it as you like. In your HTML you would use it like this.

<input ng-model="search">
<tr ng-repeat="friend in friends | filterFriends:search">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
</tr>

Here is a JSFiddle.