Comparing json results from ng-repeat against an array

Currently, I am working with a JSON result that appears in an ng-repeat and I want to filter it based on separate data objects or arrays:

Controller.js

$scope.jsonResult = [
 {
   "id": "a123"
 },
 {
  "id": "b456"
 }
]

HTML

<span ng-repeat="r in jsonResult">{{r.id}}</span>

I am trying to create another array of information and then use this data to filter the results displayed in my HTML using ng-repeat.

$scope.itemsToFilter = ["b456","foo"]

When an item matches within my itemsToFilter array and my jsonResult scope object, I do not want it to display within the ng-repeat in my HTML. Do I need to create a custom filter for this? Apologies as I am just starting out with Angular.

Answer №1

If you want to filter an array based on a blacklist of item ids in Angular, you can create a custom filter for this purpose:

angular.module("yourAppName")
.filter("filterArrayByBlacklist", function() {
    blackList = ["b456","foo"];
    return function(array) {
        return array.filter(function(item) {
            return blackList.indexOf(item.id) === -1; // item id not found in blacklist
        });
    };
});

Then, you can use this filter in your ng-repeat directive to exclude items from the blacklist:

<span ng-repeat="r in jsonResult | filterArrayByBlacklist">{{r.id}}</span>

For a demonstration, you can check out the example provided in this plnkr: http://plnkr.co/edit/VK3jiVBpL0e1G06WmPZq

Answer №2

If you're looking for a simple way to filter data, consider using a personalized filter function. You can create a basic filter like this:

$scope.customFilter = function (item) {
    return ($scope.itemsToExclude.indexOf(item.id) === -1);
};

Then, you can use the filter in your HTML like so:

<div ng-repeat="item in dataList | filter:customFilter">
    <p>{{item.id}}</p>
</div>

Check out this JSFiddle for a demonstration.

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 one convert to a boolean array in php?

I have a PHP script that I am sending data from JSON in serialized form using JQuery. PHP sees the POST data as a single associative array, which is really convenient. My question is, can I convert this data into a boolean array in PHP? And in general, is ...

Is there a way to check for invalid string literals within a string?

Looking for a way to test for invalid (unclosed) strings within a given string? This regex might help: /"[^"\\]*(?:\\[\S\s][^"\\]*)*"|'[^'\\]*(?:\\[\S\s][^'\\]* ...

The json data type seems to be malfunctioning when used in the jQuery ajax function

I am currently attempting to query the database and display the results using jQuery's ajax method. However, when I set the dataType property as json, it only logs the result that has a single object. Below is the code snippet: // Method triggered af ...

Angular: Failure in receiving EventEmitter's event with .subscribe method

My current challenge involves handling an event coming from NgLoopDirective within the method EV of NgDNDirective. I am attempting to achieve this by passing the EventEmitter object by reference and then calling .subscribe() as shown in the code snippet be ...

Tips for effectively creating and appending elements using JavaScript

Code Sample var result=$.getJSON("http://search.twitter.com/search.json?callback=?",{q:query}, function(data) { ... question. }); Query: In order to display each tweet result, I want to ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...

Guide to setting up a horizontal button menu and dropdown submenu beneath the navigation bar using Bootstrap 4

How can I design a horizontal button menu with submenus below the navigation bar in Bootstrap 4? Take a look at the image below to see what I'm aiming for: https://i.sstatic.net/j6b8a.png https://i.sstatic.net/rmtrM.png If you have any ideas or su ...

Unsure of the datatype for a particular field in a JSON object? No problem - here's how to

Working with a JSON response, I am using Jackson to parse it. However, the type of one field is unknown. For example: {"name" : "Catalina"} OR {"name" : {"First" : "Catalina", "Last" : "Kyle"}} How can I deserialize this object into a POJO? class Nam ...

Why are the elements not found by their id when I check them, even though they were created dynamically using an ajax-generated form with php-inserted values through a

How can I prepopulate form fields displayed in a modal view using jQuery after retrieving the form HTML with an AJAX query? I am trying to set the values through a JavaScript function that retrieves PHP-generated values via document.getElementById. However ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

What makes React stand out as a server side rendering technology when compared to Angular?

While delving into the world of ReactJs, I discovered a unique comparison between its rendering aspect and AngularJs. Interestingly, some refer to ReactJs as a server-side rendering technology. This revelation has truly caught me off guard! To explore fu ...

When a new VueJS project is created, it failed to automatically install the necessary basic HTML files and folders

Hey there, I am completely new to Vue.js. Just recently, I installed the Vue.js/CLI and created a brand new project using vue create test. This prompted me to choose from three options: > Default ([Vue 2] babel, eslint) Default (Vue 3 Preview) ([Vue 3 ...

Loading Three.js JSON files in Apache server

I have developed a website showcasing 3D models using JSON files with three.js. Everything works fine when I open the HTML file from my local computer. However, when I upload all the files to my Apache webserver, nothing is displayed. I attempted to run ...

Bump the version number and request a message for the commit

Recently diving into the world of Grunt, I've been experimenting with merging grunt-bump and grunt-prompt. My intention is to have users prompted for a commit message that will then be added to the commit. I looked to this article for guidance in str ...

Generating a safe POST connection with express.js

Is there a simple method to generate a link for submitting a POST request using Express.js or a plugin? This approach can also be employed to enhance security for important actions like user deletion, including CSRF protection. In some PHP frameworks lik ...

I'm encountering an issue with my API Key being undefined, despite having it saved in both an .env file and as a global variable

While attempting to retrieve information from an API, I encountered an issue where the key I was using was labeled as "undefined". However, after manually replacing {key=undefined} with the correct string in the network console, I was able to successfull ...

Storing data from PHP in Local Storage using JavaScript variable

When a specific build name is clicked, the inner HTML content is captured and assigned to a JavaScript variable called loadDump. This variable is then sent over to PHP via an AJAX request. $.ajax({ url:"http://custom-assembly.tcad.co.uk/wp-content/t ...

What happens in the React tutorial when the clear fix is commented out and the appearance does not change?

Currently, I am working through the React tutorial and have encountered a question regarding their starter code: class Square extends React.Component { render() { return ( <button className="square"> {/* TODO */} </butto ...

Controller binding is not possible without the directive 'tabset' and its controller

I'm brand new to angular, and I've hit a roadblock with directive communication. Specifically, I'm getting the error message Cannot bind to controller without directive 'tabset's controller. Here is my Code HTML code <tabset ...