Issue with Angularjs: NG-repeat and filter not functioning correctly on array

After spending the last 3 hours searching on Google and Stack Overflow, I thought this would be easy, but I'm still stuck.

I have a simple ng-repeat where I need to display everything from data2 that matches the unique ID in my data1's ref_id column.

data1: [ {id: 1, name: "Bob"}, {id: 2, name: "Diane"}, {id: 3, name: "Ross"}, {id: 4, name: "Jimbo"}, ];

data2: [ {ref_id: 1, Result: "Fries"}, {ref_id: 1, Result: "Burger"}, {ref_id: 7, Result: "Burger"}, {ref_id: 8, Result: "Nothing"}, ];

This is what I tried:

<div ng-repeat="result in data2 | filter: { ref_id: data1.id }" > {{ result.Result }} </div>

The filter seems to be not working as expected. So, I attempted to create a custom filter:

<div ng-repeat="result in data2 | filter: Test()"  > {{ result.Result }} </div>

$scope.Test = function(item){

  return angular.forEach($scope.data1, function(value, key) {
    return value.id === item.ref_id;
  }

}

However, this approach also failed as it resulted in undefined variables. I suspect it has something to do with how I implemented the function. All I want is for ng-repeat to show items with matching IDs for the ref_ID column.

Any suggestions?

Answer №1

There are a couple of ways you can achieve your goal:

1. Utilizing an `init` method

You can create a list with the necessary entries in the controller's `init` method (it's recommended to use `$onInit`), and then utilize that list in `ng-repeat`.

// Inside the app's controller
$scope.data1 = [ {id: 1, name: "Bob"}, {id: 2, name: "Diane"}, {id: 3, name: "Ross"}, {id: 4, name: "Jimbo"}];

$scope.data2 = [ {ref_id: 1, Result: "Fries"}, {ref_id: 1, Result: "Burger"}, {ref_id: 7, Result: "Burger"}, {ref_id: 8, Result: "Nothing"}];

var init = function () {
    var idList = $scope.data1.map(function (item) {
        return item.id;    
    });
    $scope.filteredList = $scope.data2.filter(function (item) {
        return idList.includes(item.ref_id);
    });
}
init();
// End of controller

In the view:

<div ng-repeat="result in filteredList"> {{ result.Result }} </div>

2. Creating a custom filter

angular.module('yourModuleName', []).filter('test', function() {
    return function(input, include, prop1, prop2) {
        if (!angular.isArray(input))
            return input;

        if (!angular.isArray(include))
            include = [];

        if (prop2) {
            include = include.map(function byProp(item) {
                return item[prop2];
            });
        }
        return input.filter(function (item) {
            return include.includes(item[prop1])
        });
    };
});
  • `input` is the list used in `ng-repeat`
  • `include`, `prop1`, and `prop2` correspond to the parameters when calling the filter

Using the filter in the view:

 <div ng-repeat="result in data2 | test:data1:'ref_id':'id'"> {{ result.Result }} </div>
  • `data2` corresponds to `input` in the filter
  • `include` corresponds to `data1` passed through the filter
  • 'ref_id' (string) corresponds to prop1
  • 'id' (string) corresponds to prop2

I found the accepted answer here and adapted it for this scenario. I hope this explanation helps.

Here's a plnkr with code examples for both approaches mentioned above: https://plnkr.co/edit/GdvVZIhDbFTaVQPY

For more information on using multiple filter arguments, refer to: How do I call an Angular.js filter with multiple arguments?

Answer №2

$scope.FilterResults = function(data){
  var idList = $scope.data1.map(function (item) {
      return item.id;    
    });
   return $scope.data2.filter(function (item) {
      return idList.includes(item.ref_id);
    });
}  
});
<div ng-repeat="result in FilterResults()" > {{ result.Result }} </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

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

Transmit ASP Webform data through Visual Studio to an external API

While working on a webform project in Visual Studio, I encountered an issue when trying to send data from the form fields to a 3rd party API using a POST request. Despite my attempts to use JSON to capture the form field data and send it as a JSON object, ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

Using jQuery and Bootstrap in an ASP.NET Core project

I am encountering an issue with the configuration of bootstrap and jquery within my project, causing these tools to fail to load properly. The problem seems to be that bootstrap is loading before jquery, resulting in error messages appearing when I check ...

JavaScript utilizing a PHP variable

In my attempt to merge a PHP variable with JavaScript, I aim to access the "the_link_to_the_page_I_want". window.onload = function openWindow() { window.open('the_link_to_the_page_I_want', 'newwindow', config='height ...

What is the best way to add 1 to a number every second with javascript?

My code seems to be functioning correctly, but I'm having trouble setting the delay and stopping the increment after a certain interval. Can someone please assist me with this? Javascript: $(document).ready(function() { var number = parseInt($(& ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

Attempting to create a child process within the renderer by triggering it with a button click

I'm currently developing an electron application where I am attempting to initiate a child node process (specifically to run a Discord.JS bot). Below is the code snippet in question: index.html: <tr> <th class="title-bar-cell" ...

Using Vue's V-IF directive to compare dates

On my website, I have an object that contains a field named available_at with the date in the format of 2019-08-08 I have a working HTML table utilizing Vue bindings but I am unsure how to compare the timestamp above using the built-in Date.now() method ...

What is the reason onbeforeunload does not fire requests in Safari browser?

Is there a way to ensure that data is saved to the database when a user interacts with the page and also when they refresh it? I have tried using onbeforeunload event, but Safari does not wait for the server request to finish before reloading the page, c ...

Learn the process of covering the entire screen with a video

I'm attempting to achieve this: IMG Below is the code snippet I've been using: <div class="container" id="containervideo"> <div id="video"> <div class="box iframe-box"> <div class="container"> ...

JavaScript function failing to validate password

While engaging in an online game where the objective is to uncover a password by inspecting the page source or element, I encountered a puzzling line: if(el.value == ""+CodeCode+""). My assumption is that el.value represents my guess, and it indicates that ...

Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts export const validateRequest = cache( async (): Promise< { use ...

Is it possible to bundle *.html templates using Require.js Optimizer functionality?

What is the best approach for packaging HTML templates (also known as 'partials') in an Angular.js app when it's concatenated and minified for distribution? Should they be included in the single file, or zipped along with other directories s ...

Transmit the data.json file to a node.js server using Postman

Hi there, I have a file named data.json saved on my desktop that I want to send to a node.js function. The contents of my data.json file are structured as follows: [{"key":"value"}, {same key value structure for 8000 entries}] This fil ...

After reaching the conclusion, the code restarts

Any ideas on how to reset this code every 10-20 seconds? I'm struggling to find a solution! I'm new to coding, so any assistance would be greatly appreciated. Here's the code: var items = document.getElementsByClassName('btn-primary n ...

Is it possible to include a module-level controller within a directive?

I am currently navigating the complexities of controllers, modules, and services in Angular JS. In my attempt to integrate a controller into my directive, I faced an issue. The controller I intend to reference belongs to the same module as the directive, ...

Ways to add elements to the DOM using jQuery from the local storage?

I'm facing a challenge where I have an input field and store the inputs in local storage. When I click on 'add', I want to immediately append the new inputs to my ul element. However, simply appending the current input won't work as it ...

I am having trouble comprehending this JavaScript code, could someone provide me with assistance?

Currently delving into the world of JavaScript functions and stumbled upon this code snippet with the following output: Output: "buy 3 bottles of milk" "Hello master, here is your 0 change" function getMilk(money, costPerBottle) { ...

Guide to saving an http response as a file and automatically retrying on a 503 error

When it comes to piping the response of an http request to a file, the process is pretty straightforward: http.get(url, function (res) { var file = fs.createWriteStream(filename) res.pipe(file) file.on('finish', function () { file.clos ...