Using AngularJS to apply filters to JSON data

I'm having trouble filtering a JSON array. Here's an example of what my JSON array looks like:

vm.users = [{ "fname": "Antoan", "lname": "Jonson", "Address": "Address1" }, ... ]

How do I filter by last name starting with a specific term (e.g. 'Jo')? I've tried the following code snippet:

angular.module('MyApp', ['ngMaterial', 'ngMessages', ])
.controller('AdminController', function ($scope, $http, $filter, $location,  $sce) {
MyApp.filter('myFilter', function () {

    return function (input, term) {
        var output = [];
        angular.forEach(input, function (value, index) {
            if (value.lname.startsWith(term)) {
                output.push(value);
            }
        });
        return output;
    }
});
});

Answer №1

create a personalized filter

myApp.filter('customFilter', function() {

return function(input, keyword) {
    var result=[];
    angular.forEach(input,function(val,index){
        if(val.lname.startsWith(keyword)){
            result.push(val);
        }
    });
    return result;
}
});

implement the custom filter by using

var filtered = $filter('customFilter')(JSON.parse(vm.users), term);

Answer №2

Give this a shot:

vm.users.filter(function (user) {
  return user.lastname.includes(term);
});

Let me know if this works for you.

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

What is the best way to conceal certain choices in a dropdown menu?

How can I display only the cities in Australia in a dropdown list? I have tried to find "Australia" in the options and hide everything before and after it, but I have been unsuccessful! Here is my fiddle. <select class="dropdown" id="dropdown"> ...

The button text in Bootstrap 5 is black instead of white as shown in their demo

During the installation of Bootstrap 5, I encountered an issue where many of my buttons are displaying a black font instead of the expected white font as shown in the Bootstrap 5 Documentation For instance, the .btn-primary button on the official Bootstra ...

What is the method to detect the presence of any value from one array in another array using AngularJS?

In my AngularJS factory method, I am creating a permission function to check the user's role. If the user object contains the specified role, the result should be true; otherwise, it should return false. Here is an example of my user object: administ ...

What is the best way to display my to-do list items within a React component

I'm working on a straightforward todo application using fastapi and react. How can I display my todos? I attempted to use {todo.data}, but it's not functioning as expected. Here is my Todos.js component: import React, { useEffect, useState } fro ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

Issue arises when trying to utilize Ajax on the Fancy Box overlay button click and the functionality does not perform as

Hey there! I've got a bit of a silly question for you. So, I'm pretty new to Ajax and fancy box. I've been using fancy box on one of my pages, and it's been working well so far. The issue I ran into was when I tried to make an ajax call ...

Send Summernote code data using Ajax to PHP which will then store it in the database

I have implemented a Summernote editor on a page where users can input content. When a user submits the page, I use jQuery to retrieve the HTML code from the editor and then send it to a PHP script for insertion into a database. The HTML retrieved before s ...

Can you tell me the appropriate type for handling file input events?

Using Vue, I have a simple file input with a change listener that triggers the function below <script setup lang="ts"> function handleSelectedFiles(event: Event) { const fileInputElement = event.target as HTMLInputElement; if (!fileInp ...

Encountering a TypeError message stating that "selector.includes is not a function" while attempting to scrape using cheerio and

Trying my hand at web scraping with the code snippet below: const cheerio = require('cheerio'); const jsonframe = require('jsonframe-cheerio'); const $ = cheerio.load('https://coinmarketcap.com/all/views/all/'); jsonframe($) ...

`AngularJS-Infused Panoramic Experience on Windows Phone`

Currently, I am working on incorporating the design of Windows Phone Ui into an AngularJS application. To get a visual idea of what the Windows Phone Ui looks like, you can check out this example. Endless Swiping Feature An interesting feature of the W ...

What is the most effective method for populating data within a browser window?

I have a list of files stored in $scope.data that I retrieved from the searchFactory. Now, my goal is to display these files in the browser window. How can I accomplish this task? ctrl.js $scope.displayFiles = function (){ $window.open($scope.dat ...

Utilize the click spinner feature on a single button in Angular

I have a table with a list of items and each item has a button to request a PDF document from the server. I want to show a spinner while waiting for the document to be received. Currently, when I click on a button, the spinner appears on all buttons instea ...

Steer clear of cross-domain solutions

Currently, I am developing a web application that allows customers to integrate it into their websites by linking to a JavaScript file on my server. Despite the application reading all JavaScript files from my server, I encounter an error when attempting t ...

Display a div element on the page after 10 seconds of loading

Recently, I managed to get this script working successfully where it fades out within 20 seconds. However, I am looking to modify it so that it takes only 10 seconds to display after the page loads. Any suggestions on what I should change in the code? jQu ...

What is the best way to trigger an action in response to changes in state within Vuex

Are there more sophisticated methods to trigger actions in vuex when a state changes, rather than using a watcher on that state? I want to ensure the most efficient approach is being utilized. ...

What are the steps to create a dynamic navigation bar in React without encountering hydration issues?

My goal is to dynamically show or hide links based on user authorization. Here's my initial approach: const Navbar = () => { const { canDo, ...} = useUser(); //A Zustand store return ( <> <div> <ul> ...

Angular NVd3 barChart with multiple bars

I am trying to implement the nvd3 angular multiBarChart, but I am struggling with the lack of documentation. Despite searching on Google and Stack Overflow, I haven't found a solution that fits my specific scenario. My question pertains to how to stru ...

Using a string as a query parameter in Javascript/AngularJS

Hey there! I have a username that I'm passing to retrieve a record from the database. Here's what I have in my controller: $scope.team=function(data) team_factory.getMember.query({}, data.username, function(data){ $scope.team=data; }); And ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Could anyone assist me in resolving the error stating, "The 'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments"?

Upon investigating, I inserted this console log to determine what data is being received: { username: 'aa', gender: 'Feminino', cargo: '2', email: 'a', password: 'a' } Lately, I've been facing this err ...