Display only the relevant search results using ng-show in AngularJS

By utilizing the code below, I am able to filter results where all entries are displayed 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>

I am aiming for a jQuery UI autocomplete-style solution where initially there is nothing on the page, but as you type, matching entries appear.

I have attempted to achieve this using ng-show. So far, my only success has been with something like:

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

This means the content will only display if "John" is typed. Is there a way, perhaps with ng-show or ng-if, to dynamically filter and display matching entries as you type, similar to how the filter works?

I have included an example showing my attempt with the name "John":

    <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 have also tried:

ng-show="searchText == searchText"

However, this just displays all items. Can this functionality be achieved with ng-show? Or is there a better approach?

Answer №1

If you're looking to create a personalized filter, it's a simple process. This particular filter will compare your friend's name with the search term. If

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

This snippet demonstrates how filters can be constructed, and you have the freedom to customize it according to your preferences. When implementing this in your HTML, it would look something like this.

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

You can also view a JSFiddle example here.

Answer №2

Instead of complicating things, you could simplify by using:

<tr ng-repeat="friend in friends" ng-show="([friend] | filter:search).length > 0">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
</tr>

This setup ensures that the filter affects all properties, not just the name.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

Can the performance of a system be impacted by node.js cron?

I am looking to incorporate a cron module (such as later or node-cron) into my node server for job scheduling. The jobs in question involve sending notifications (e.g., email) to remind users to update their profile picture if they haven't done so wit ...

Verify if there are any repeated values in a text input field within an Angular form

Hello everyone, I've encountered an issue with a text field in a form. I want to validate the input against an array of values to ensure it's unique, but as a newcomer to directives, I'm feeling a bit overwhelmed. <input type="text" ng- ...

display in a modal-body and jdata

Within my MySQL database, there are several columns stored, including: headline, description, place, resume Currently, I am able to display the headline and description in a modalbox using the following code. However, I now wish to also showcase the pl ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

Having trouble resolving the signature of a class decorator when invoked as an expression with @Injectable in Angular

Error Message: Unable to resolve the signature of a class decorator when called as an expression. The argument type 'ClassDecoratorContext' is not compatible with the parameter type 'string | symbol | undefined'. After creating a book ...

Is there a way to prevent Faker from continuously displaying the identical picture?

One of the challenges I'm facing involves using faker to generate an array of random objects. Here's a snippet of what I have: { "image": faker.random.arrayElement([ faker.image.nature(), faker.image.city(), faker.image.food() ...

This message is designed to validate the form as it is dynamic and

Is there a way to dynamically determine which .input fields have not been entered yet? In the following code snippet, you can observe that if I input data out of sequence, the #message displays how many inputs have been filled and shows the message in sequ ...

Troubleshooting minified JavaScript in live environment

Trying to wrap my head around AngularJS and Grunt. In my GruntFile.js, I have set up two grunt tasks for development and production. In production, I am using uglification to combine multiple js files into one. I am in need of some advice or tips on how t ...

Enhancing Vue Filtered Lists for Increased Dynamism

Currently, I am iterating through a list of items using the v-for directive. Before displaying the list, I apply a filter based on a specific value using the .filter() method. To switch between different filtered values, I utilize the v-on:click event. How ...

Choosing multiple images using JavaScript/jQuery

Gridster is being used for a webpage, with widgets containing images that can be added and deleted using the "+" and "X" buttons. Current Status Clicking the "+" button opens a modal where multiple images can be selected and added to the widgets by click ...

Deciphering the mechanics of collection referencing in mongoose

Today, I am delving into the world of using references in mongoose for the first time. I am trying to figure out how to save a template with a user ID. Do we need to retrieve the createdBy value from the client, or can it be inserted into the templateSchem ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

Display a text field when the onclick event is triggered within a for

Control Panel for($i = 1; $i <= $quantity; $i++){ $data .= '<b style="margin-left:10px;">User ' . $i . '</b>'; $data .= '<div class="form-group" style="padding-top:10px;">'; $data .= ' ...

Patience is key when awaiting the completion of several promises

I am currently utilizing the SQLStorage feature provided by the Ionic platform. The remove function within this tool returns a promise. Within my code, I have a need to remove multiple values and then execute some additional code once all removals are comp ...

The watermark feature in HTML may not appear when printed on every page

I'm facing an issue with adding a watermark style. The watermark displays only on the first page when attempting to print in Chrome. It works perfectly in Firefox and IE. <style type="text/css"> #watermark { color: #d0d0d0; font-size: 90pt; ...

Hold off on advancing until the particular text is found in the DOM element

One of the challenges I'm facing is creating a function that waits for specific text to change before returning a value: function getElementText() { while(isLoading()) { } return $('#element').text(); } function isLoading() { ...

What are the differences between ajax loaded content and traditional content loading?

Can you explain the distinction between the DOM loaded by AJAX and the existing DOM of a webpage? Is it possible to load all parts of an HTML page via AJAX without any discrepancies compared to the existing content, including meta tags, scripts, styles, e ...

Command to exclude the processing of an element during compilation

I'm working on creating a custom directive named ng-ignore that will block the HTML compiler from processing an element and its children. While I've been honing my skills in directive writing, this particular one has me a bit puzzled. My object ...