What is the best way to sort through items in ngRepeat based on an array of numbers?

I'm having trouble figuring out how to filter a list of results in an ng-repeat based on an array of numbers. These numbers can determine which results I want to display or hide. Currently, I am able to use a filter in the view to filter by one number, but I would like to be able to filter by an array instead. Whether the filter is in the view, controller, or a separate filter does not matter to me.

The following code successfully filters topics with the forum ID of 60

  <div ng-repeat="topic in topics | filter:{forum_id:60}">
    Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
  </div>

Now, I want to be able to filter by an array

  <div ng-repeat="topic in topics | filter:{forum_id:ARRAY_HERE}">
    Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
  </div>

For the complete example, please visit: https://plnkr.co/edit/dCZ7DV?p=preview

Answer №1

Implement a custom filter function:

<div ng-repeat="subject in subjects | filter:myCustomFilter(subject)">
    Subject ID: {{subject.subject_id}} Subject Name: {{subject.subject_name}}
</div>

In your controller:

$scope.myCustomFilter = function() {
    return function(item) {
        return $scope.filteredSubjects.includes(item.subject_id);
    }
}

Check out the updated plunkr here

Answer №2

You have the option to employ the ng-if and indexOf functions for achieving this task.

<div ng-repeat="topic in topics" ng-if="filterBy.indexOf(topic.forum_id) !== -1">
     Forum ID: {{topic.forum_id}} Forum Name: {{topic.forum_title}}
</div>

Check out the Demo here

Answer №3

By default, the filter property in Angular does not operate in that manner, requiring you to create a custom filter.

You can achieve this by following the instructions provided here

angular.module('myApp').filter('selectedArray', function() {
    return function(array, tags) {
        return array.filter(function(object) {

            for (var i in object.XXX) {
                if (array.indexOf(object.XXX[i]) !== -1) {
                    return true;
                }
            }
            return false;

        });
    };
});

After defining the filter, you can utilize it like so:

<ul>
    <li ng-repeat="task in tasks | selectedArray:Array"></li>
</ul>

Given that this example assumes the response is an array of objects, you may need to customize it to fit your specific array structure.

We hope this explanation proves helpful.

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

Guide on accessing the text content within a div element in HTML by triggering a button click

To extract specific text from multiple div tags, I need to trigger an event when clicking a button. <div class="col-lg-3 col-md-6 mb-4"> <div class="pricing-table pricing-secondary"> <div class="price-hea ...

Retrieving information from a JSON document in IONIC with the help of AngularJS

Issue After using the ionic tabs template to create my first project with the ionic framework, I noticed that the data for friends and friend details is being pulled from an array list in the services.js file. However, I would like to instead fetch this d ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...

Failed to connect to Wordpress REST API when calling it from a NextJS server due to ECONNREFUSED error

I am currently working on a basic example that involves fetching a list of page slugs from the WordPress REST API, but I am encountering some unexpected behavior. My getPageList() function is an asynchronous function that makes a simple call to the WP API ...

Garbage collection is failing to release objects stored in the global array

Question regarding memory management in a JavaScript program. In my code, I have a global array called g_objArr, which is used to store customer profile details. This array contains objects with various customer information fields. The issue arises when ...

Assistance Needed with Array Coding for Bouncing Ball Exercise in Class

Embarking on a journey into Java programming with a Processing twist, I find myself delving into the bouncing ball assignment for beginners. Successfully getting it to move correctly and encapsulating it within a class was a milestone achieved, but alas, t ...

Utilizing JQuery Autocomplete to Display Names and Retain IDs with PHP and MySQL

I am facing an issue with the autocomplete feature where the list appears blank (only borders, no content). Here is the code snippet: The Data I receive : <?php require 'cnx/cnx.php'; $stmt = $pdo->prepare('select * from auteurs w ...

Determine the position of the anchor/hash in the document

I am really struggling here. Whenever I try to enter index.html#about (or bookmark it and open it), I need to extract the index() of this and place it in the script below as "slideNumber". HTML Structure <div id="slideshow"> <div id="frontp ...

How can I retrieve information from a Behavior Subject within an Angular service?

My goal in using BehaviouSubject was to streamline API calls and share the data with multiple components within the same route. While I've successfully achieved this, I'm facing challenges when trying to filter the received data. Here is a stack ...

Struggling with a simple numpy question - how to add a 2D array to a 3D array

I am struggling with merging a 2D array of size (X, Y) to a 3D array of size (X, Y, 8) in a way that the resulting array has dimensions of (X, Y, 9). Despite trying various methods such as append, concatenate, dstack, and column_stack(), I keep encounter ...

Modify the text in a paragraph by clicking on a link using JQuery and HTML

I'm attempting to implement a straightforward action, but I'm facing some challenges. My navigation bar consists of a few links followed by a text section. What I aim for is that when I click on a link, the paragraph of text should change to refl ...

Tips for looping through a JSON response in Angular 2

I received a response from a service containing form definition in JSON schema format. https://i.sstatic.net/BTHJM.png Now, I need to iterate through this response in an Angular component. Firstly, I fetched all the schema elements into a Formdata varia ...

The mysterious case of the missing CSS file in Node.js

I recently set up a new Node.js Express Project. However, I am facing an issue with the index.ejs file showing the error: Undefined CSS file ('/stylesheets/style.css'). Here is the content of the index.ejs file: <!DOCTYPE html> <html& ...

Look for specific terms within an array of words

Hello, I am facing a challenge with searching for words that contain at least part of another word in JavaScript. Specifically, I need to find words in an array without using built-in functions like index.of, slice, substr, substring, or regex. Can only us ...

There is an issue with the sorting function: [orderBy:notarray]. The expected input was an array

Looking to incorporate pagination functionality from this source: http://jsfiddle.net/SAWsA/11/ [ { "name": "Micro biology", "id": "2747c7ecdbf85700bde15901cf961998", "category": "Other", "type": "Mandatory - No Certification", "cate ...

What are some examples of utilizing the hash feature in AngularJS when using $q.all?

After researching extensively, I have come up empty-handed in my search for a clear explanation on how to utilize this feature. The provided documentation states: This method returns a single promise that will return an array or hash of values, each val ...

Event that occurs when modifying a user's Firebase Authentication details

Monitoring User Actions with Firebase Authentication Within my application built using Angular, Node.js, and Firebase, I am seeking a method to track user events such as additions, modifications, and deletions. Is there a mechanism to recognize when a us ...

How can I automatically direct my NodeJS application to the login screen?

Here is the setup of my project structure: There is a simple folder called static, within which I have: index.html (the homepage for user registration) login.html (the login page) In the parent folder, there is a file named server.js: // NodeJS code for ...

What is the method for inserting a new key value pair into every object within a PHP multi-dimensional array?

Seeking a way to iterate over an existing multi-dimensional array and conditionally append a new item to each object within the array. If we have the original Array as follows: Array ( [0] => Array ( [id] => 4 [uid] >> 1 ...

Tips for utilizing the "Enter" key rather than the "Tab" key in OpenERP 7 for a one2many field

I am currently working on the sale order line functionality, and I have a specific requirement. When I press the "Enter" key in a one2many field, a new line is created. However, I would like to customize this behavior so that the "Enter" key functions as t ...