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

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...

Guide to incorporating @types/module with the corresponding npm module that has type definitions available

This is an example of a module I am currently utilizing in my project. I have come across TypeScript type definitions for the npm module polylabel, which can be found at https://github.com/mapbox/polylabel. When I run npm install --save @types/polylabel, ...

Transforming specific symbols (é è ë) with URL encoding

I am currently working on a JavaScript function that opens the user's email client with pre-filled content. However, I am facing difficulties in converting special characters so they display correctly in the email client (especially when passed throu ...

Having trouble accessing an element after parsing JSON using jQuery, ending up with an "

Here is a snippet of code with a text and a button: <div id="divtest"> <h1> Bla </h1> </div> <button id="dugme1"> dugme </button> When the user clicks the button, the following script will be executed: $("#dugme1").cl ...

Using THREE.js to incorporate a stroke above extruded text

Looking to enhance text with a horizontal line above it: var geo = new THREE.TextGeometry("x", geometry_options); var mat = new THREE.MeshBasicMaterial({color: 0, side:THREE.DoubleSide}); geo.computeBoundingBox (); var vec = new THREE.Shape(); vec.moveTo( ...

socket.io initialization and finalization events

Currently, I am integrating socket.io with express 3 for my application development. I am interested in implementing loader animations that will appear when a message is incoming and disappear once the message has been received. Similar to how jQuery&apos ...

Tips on managing PDF files from a Web API in AngularJS

I have implemented a Web API post method for generating a PDF: [HttpPost] [Route("api/pdf")] public HttpResponseMessage Post(CustomType type) { StreamContent pdfContent = PdfGenerator.GeneratePdf(); HttpResponseMessage response = new HttpResponse ...

Leveraging the power of Ajax and Javascript to handle and process conditional if/else statements

Hey there, I'm new around here so I hope I got this right. Currently, I'm diving into the Ajax for Dummies book after enjoying the PHP one years ago. However, I've hit a roadblock with my first real Ajax program. It took me ages to locate th ...

Utilizing PHP and jQuery to dynamically populate Google Maps with multiple markers

I am currently working on integrating a Google map with a database to dynamically display multiple markers using PHP and MySQL. Below is the code I have been using: <?php //This section retrieves data from the database for later use in jQuery //CREATE ...

A React component that exclusively renders component tags

After successfully loading index.html with no JavaScript errors, I ran into an issue where nothing was rendering on the page. Upon inspecting the webpage, all I could see was a tag and nothing else. It turns out that I have a component called "list". The ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Customizing textfield error color in MUI5 React based on conditions

I am looking for a way to dynamically change the color of error messages in my application, with warnings displaying in orange and errors in red. I prefer not to use useStyle as it is now deprecated in mui5. Below is the code snippet I have created: import ...

Angular2 recursive template navigation

Is it possible to create a recursive template in Angular 2 without using ng-include? It's puzzling why this feature seems to be missing in Angular 2... HTML: <div ng-app="app" ng-controller='AppCtrl'> <script type="text/ng-templat ...

My eCommerce website is currently experiencing some technical difficulties that need to be addressed

I'm in need of assistance with a particular error I encountered. I was following an ecommerce example application and everything seemed to be going smoothly until I clicked on "Shop Now." At that point, I received the following message: Server Error T ...

Ways to display output on a single line using javascript

It seems like such a simple task, but no matter how I try, I cannot get proper spacing between my words. /s does not seem to work for me. Here is an example of what I have attempted: document.write('You have been alive' + */s userMsDays /s* + &ap ...

Having trouble establishing a basic websocket connection in NodeJS

I am currently following a tutorial on WebSocket protocol development from this link: . Upon visiting localhost:1337/index.html, I encountered the following error: This localhost page cannot be found. No webpage was found for the web address: http://loc ...

Is there a way to update my profile picture without having to constantly refresh the page after uploading it?

Here is the code for my profile page. I am considering using a callback along with another useEffect function, but I'm unsure. Please help me in finding a solution. For now, let's ignore all the code related to deleting, saving, and handling ingr ...

What steps should be taken to complete orders following the checkout.session.completed event triggered by Stripe?

Having an issue with Stripe's metadata object that has a limit of 500 characters. My checkout flow is operational, but the only constraint is the character limit for my cart. I need to include extras and customer notes in my cartItems object for each ...

Having trouble with the CSS positioning of divs created with JavaScript: it's not behaving as anticipated

Let me start by saying I have always struggled with CSS positioning. It seems like I am missing something simple here... So, I have a JS script that generates divs within a parent container called #container which is set to absolute position. Here is the ...

When trying to display data using ng-repeat on a different user's profile page, I'm having trouble getting it to show up

My goal is to retrieve data when a user clicks on a username, redirecting them to their profile page. I'm attempting to achieve this using ng-click as shown below: <p style="font-size:11px; color: grey; " ng-click="seeProfile(gterest);changelocati ...