Angularjs custom filter for both short and full names

I am working on creating a filter that can filter by both short names and full names.

So far, I have successfully implemented filtering by full name using AngularJS:

angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        'Indian Overseas Bank',
        'Housing Development Finance Corporation',
        'Industrial Credit and Investment Corporation of India',
        'Indian Bank',
        'City Bank',
        'City Union Bank',
        'Kotak Mahindra Bank',
        'Tamilnadu Mercantile Bank ',
        'State Bank Of India'
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>

<div ng-app="myApp" ng-controller="namesCtrl">

<p>Type a letter in the input field:</p>

<p><input type="text" ng-model="test"></p>

<ul>
  <li ng-repeat="x in names | filter:test">
    {{ x }}
  </li>
</ul>

</div>

Now, my challenge is to figure out how to filter by short names like IOB, HDFC, SBI.

The desired outcome would look like this:

Filter word     : Expected result 

IOB             : Indian Overseas Bank 
HDFC            : Housing Development Finance Corporation
SBI             : State Bank of India
ICICI           : Industrial Credit and Investment Corporation of India'

Please note: All banks mentioned are Indian banks. When filtering by SBI and ICICI, common words such as of, and should not affect the results.

Additionally, if I enter a generic term like India, I expect the same filtering behavior as seen in the existing code snippet. How can I achieve this?

Answer №1

It seems like a custom filter is required for your task of abbreviating words and matching them with a given model. Using the .indexOf() method could be helpful in this scenario.

Take a look at this demonstration:

var app = angular.module('myApp', []);
app.filter('myFilter', function() {
  return function(inp, model) {
    if (!model) {
      return inp;
    }
    var ignore = ["of", "and", "Of", "And"];
    var array = [];
    for (var i = 0; i < inp.length; i++) {
      var str = "";
      var arr = inp[i].split(" ");
      for (var j = 0; j < arr.length; j++) {
        if (ignore.indexOf(arr[j]) == -1) {
          str += arr[j][0];
        }
      }
      // str = str.toLowerCase();
      // model = model.toLowerCase();
      if (str.indexOf(model) != -1) {
        array.push(inp[i]);
      }
    }
    return array;
  };
});
app.controller('namesCtrl', function($scope) {
  $scope.names = [
    'Indian Overseas Bank',
    'Housing Development Finance Corporation',
    'Industrial Credit and Investment Corporation of India',
    'Indian Bank',
    'City Bank',
    'City Union Bank',
    'Kotak Mahindra Bank',
    'Tamilnadu Mercantile Bank ',
    'State Bank Of India'
  ];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="namesCtrl">

    <p>Type a letter in the input field:</p>

    <p><input type="text" ng-model="test"></p>

    <ul>
      <li ng-repeat="x in names | myFilter:test">
        {{ x }}
      </li>
    </ul>

  </div>

</body>

</html>

(Please note that the example is case sensitive)

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

AngularJS pulls data that is preset on the blade to be initialized within the controller

I am working with a Laravel Blade table that has an initialized value which I need to access in the controller in order to send it to a function to make an API call. How can I access the ID that is sent? app.controller('MyController', ['$sc ...

Why is the second row of inputs not displaying in Vue.js?

I am currently developing a Single Page Application (SPA) that includes options with variants, similar to the image shown below: [1]: https://i.sstatic.net/82I5U.png However, I have encountered an issue where the second row of inputs for variants is not b ...

Make the adjustment from an H1 tag to an H2 tag with the help of

I need assistance with changing the HTML code from using an <h1> tag to a <h3> tag, using Vanilla JavaScript. Here is the code snippet in question: <h1 class="price-heading ult-responsive cust-headformat" data-ultimate-target=" ...

Tips for displaying a script file from a remote server on your PHP page using AJAX

I'm currently working on executing a script from a remote server and displaying the output on an HTML page using AJAX for user visibility. I managed to do this successfully on my local server with up.sh and down.sh scripts. However, when attempting th ...

Automatically setting the checkbox for each unique ID based on database values for the specified hobby

Query: The issue I am facing is that when I click the edit button for the first time, the checkboxes get checked based on the values in the database table. However, when I click another edit button for the second time, the checkboxes do not get unchecked f ...

How to change the color of the tooltip text in Bootstrap Vue

In an attempt to modify the color of the tooltip text from its default to red https://i.sstatic.net/fF78X.png Any payment made during the night hours (00:00 – 06:00) must be displayed as red. ...

Taking input strings using the C programming language

My goal is to enhance my coding skills by working on a small program that reads a text file and stores its contents in an array. The program is designed to accept any text file and convert it into a string, storing it dynamically in an array. This exercise ...

update the dropdown values in the database by submitting the form

Members sign up for the website. The administrator will log in and access a list of users. I am attempting to provide an option for the admin to select a checkbox and update the user's status through a dropdown menu submission. When I tested the code ...

html elements correspond directly to individual json objects

Looking for a precise way in javascript/jquery to connect objects created in an external JSON file to populate their respective HTML divs. The code snippet and JSON data are provided below, along with an image for reference that shows the layout of the div ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

Issue with series of node commands getting stuck on npx command

I have a custom node script that I use to automate the setup of my application. This script creates directories, generates files, and executes a series of node commands. Everything functions correctly for the most part. The specific commands being executed ...

Why isn't the router returning JSON data?

Why am I not receiving a response from this code? const express = require('express') const mongoose = require('mongoose') const authRouter = require('./authRouter') //importing the router const PORT = process.env.PORT || 3000 ...

conceal the input once the button is clicked

Here is my code snippet: while ($row = $result->fetch_assoc()) { $id = $row['id']; ?> <script> $(document).ready(function(){ $("#btn<?echo $id?>").click(function(){ $(" ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...

Node and Express fail to set cookie when used with Nginx server

I am encountering an issue with setting a cookie in my Node app using Express. The cookie sets successfully in the local environment (http), but when deployed to production (https), although I can see the cookie in the response, it is not actually being se ...

Guide on utilizing $q for retrieving a promise from a $broadcast within angularJS

Currently, the controller code I've written is structured like so: $scope.spAPI.load(id).then(function(result){ var deferred = $q.defer(); if(result !== undefined){ deferred.resolve($rootScope.$broadcast("onSpLoaded", result)); } return de ...

The presence of 'touched' within Angular validation is causing a delay in method execution

Upon utilizing this validation method, it became apparent: <label>Password</label> <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touc ...

The outputs of base64(sha256(data)) from nodejs crypto and CryptoJS are showing discrepancies

In my setup, I have a node server and a react-native app. The node server utilizes the crypto module for all cryptographic operations, while the react-native app relies on the crypto-js library due to the unavailability of crypto. You can find a sample co ...

Struggling to determine if the checkbox has been ticked?

I have integrated a like button on my website using socket io to ensure that it updates for all users when the like button is clicked. I have successfully implemented a like() function that emits liked, increments a counter, and displays it on the page. Ho ...

Can the useEffect hook prevent the page from rendering?

Is there a way to have a slight delay every time the user visits or reloads the page in order to allow for content loading? Currently, I am using a useEffect() with a setTimeout() function that sets the variable isLoading to false after 1 second. However, ...