Creating a specialized filter for AngularJS or customizing an existing one

AngularJS filters are great, but I want to enhance them by adding a function that can check if a value is in an array.

For example, let's say we have the following data:

Queue = [
    {'Name':'John','Tier':'Gold','Status':'VIP'},
    {'Name':'Anna','Tier':'Silver','Status':'Normal'},
    {'Name':'Luke','Tier':'Gold','Status':'Normal'},
    {'Name':'Mary','Tier':'Bronze','Status':'Normal'},
    {'Name':'Jess','Tier':'Bronze','Status':'VIP'},
];
Priority = ['Gold','Silver'];

I want to display the names of Priority members who are also VIPs.

<div ng-repeat="people in Queue | filter: {Tier:Priority} | filter: {Status:'VIP'}">{{ people.Name }}</div>

I would like to update the filter so it can compare Tier with items in the Priority array.

I've tried creating a custom filter with AngularJS, but I'm struggling to make it as versatile as the existing one, which can handle objects, strings, and functions seamlessly.

My focus isn't just on checking if an item exists in an array, but on developing a filter that can differentiate between strings and arrays while maintaining the functionality of the current filter.

Answer №1

To implement a custom filter, I will utilize regular expressions in this scenario.

Within the .html file:

<body ng-app="myApp">
   <tr ng-repeat="item in Queue | regex:'Tier':Priority | filter:{Status :'VIP'}">
</body>

The custom filter code is as follows:

var myApp = angular.module('myApp', []);
myApp.filter('regex', function() {
  return function(input, field, priList) {
     var result = [];
     var priListExp = priList.join("|");
     var patt = new RegExp(priListExp, "i"); // remove "i" for case sensitive
      input.forEach( function(pri){
         if(patt.test(pri[field])) {
           result.push(pri);
         }
     });

  return result;
  }
});

See the demo here: Plunker

Answer №2

Here's a concept, not an operational code snippet. If you provide arguments in the filter function, you could implement it like this:

module.filter('filterName', function() {
return function(input, tier, status) {
 if (input.Tier == tier)
 {
  //perform action
 }
 if (input.Status == status)
 {
  //perform action
 }
 return input;
}   
});

In your HTML:

<div ng-repeat="people in Queue | filterName:'Priority':'VIP'">{{ people.Name }}</div>  

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

Can a Vue app be created as a standalone application?

Can a Vue application be created without requiring Vue as a runtime dependency? For example, rather than having the browser load vue.js and the app like this <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src= ...

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

Developing a user authentication system with TowerJS

As a front-end designer/developer with limited MVC experience, I am looking to create a login form using TowerJS. Following the documentation, my app includes a model named "User": class App.User extends Tower.Model @field "email", type: "String" @fie ...

Angular 5's external JavaScript library

After thoroughly researching this subject, I find myself still lacking comprehension. An example may be the key to understanding. As a newcomer to Angular, my goal is to create a mathematical application for mobile using Ionic. Despite investing two weeks ...

What is the method for adding line breaks to a JSON file?

I've been developing a Discord bot and I'm currently storing currency values in a json file. The functionality is working smoothly, but the issue I'm facing is that it's adding them to the json file in a single line which makes it diffi ...

Error: User cannot be used as a constructor

When attempting to register a user using a Node.js app and MongoDB, I encountered the following error message: const utente = new Utente({ ||||| TypeError: Utente is not a constructor This is my model file, utente.js: const mongoose = require("mongoose") ...

What causes variables and functions to behave differently when it comes to hoisting?

I've recently been delving into some documentation and have noticed some inconsistencies in hoisting patterns within JavaScript. Consider the following examples: When it comes to functions, function abc(){ console.log("worked") } abc(); OUTPUT : ...

The Django application is failing to interact with the AJAX autocomplete functionality

After typing the term "bi" into the search bar, I expected to see a username starting with those initials displayed in a dropdown list. However, nothing is showing up. Here are the codes I have used: search.html <html> <div class="ui-widget"> ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

The click event that is dynamically added is triggered multiple times

On clicking a button, I am dynamically adding a row to an HTML table. The row contains a cell with a list item (li) element which has a click event assigned to it. However, when I click on the list item, the event fires multiple times and I'm unsure w ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

What steps can I take to ensure my dashboard table is dynamic, updates in real-time, and automatically reflects changes made in my MySQL database

FrontEnd Code import React, { Component, useState, useEffect } from "react"; import Navbar from "../Navbar/Navbar.js"; import BarChart from "../BarChart/BarChart"; import { Chart, Tooltip, CategoryScale, LinearScale, ...

The privateroute is throwing an error because it cannot access the property state since

I stumbled upon a tutorial online detailing how to construct a customized private route, but alas, I am encountering an error. Upon execution, I am faced with the dreaded message: "Cannot read property 'state' of undefined" on line 12. As someon ...

"Unlocking the JSON element with jQuery Ajax: A step-by-step guide

I am trying to pinpoint a specific element within my JSON data: { "taskMeta": "Some meta info", "tasksLib": [ { "task001": { "id":"1", "createDate":"01.02.17", "dueDate":"02.03.17", "au ...

When submitting forms in AngularJS, make sure to include empty fields as null values instead of excluding them entirely

Check out my HTML / Angular code below: <form ng-submit="ctrl.add()"> <div class="form-group"> <label>Username</label> <input type="text" ng-model="ctrl.user.username"> </div> <div class ...

Attempting to implement usedispatch hook in combination with userefs, however, encountering issues with functionality

I've been exploring the Redux useDispatch hook lately. I created a simple app for taking notes in a todo list format. However, I am facing an issue with useDispatch as it's not working for me and I keep encountering this error: Module build faile ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

Reversing the sequence of code in JavaScript - react native

I'm currently working on tracking the number of times a button is pressed within one second. For the most part, it's functioning correctly as it tracks and displays the count. The issue arises when it displays the button press count from the pr ...

How can we effectively share code between server-side and client-side in Isomorphic ReactJS applications?

For a small test, I am using express.js and react.js. Below you can find my react code: views/Todo.jsx, var React = require('react'); var TodoApp = React.createClass({ getInitialState: function() { return { counter: 0 ...

Dealing with Large JSON Strings in ASP.NET MVC Views

Large JSON Objects (approximately 1.5 MB) are received in Controller C1. They are then converted to strings and stored in a hidden label in View V1. The JSON data in V1 is utilized by parsing it in JavaScript J1. An occurrence of Out of Memory Excepti ...