Tips on using an array filter in AngularJS ng-repeat

I have successfully used ng-repeat to display my data.

Within the ng-repeat result set, one of the data fields is an array of items. Example: {x:1, y:[2,3,4]} I want to filter the data based on the values inside the array. Filtering by non-array data is easy, but I am struggling with filtering by values within the array.

Here is the markup I am using:

ng-repeat = "con in cons | filter: usrSingle.username in con.conPlayerList"

(adjusted markup for better example matching

ng-repeat = "con in cons | filter: '3' in con.y"
)

usrSingle is a scope accessible in this controller. I am not receiving any errors, but I'm unable to find relevant examples for this issue.

Additional code has been requested, so here it is below. I should mention that this is a MEAN app, with MongoDB serving the data and a REST API for data calls.

(EDIT) code snippet from the angular module:

// API call for data
app.factory('usrService', function ($resource) {
return $resource('/api/users', {});
});
// factory for storing user data across controllers
app.factory('usrTracker', function () {
var vUsrProfile = {
    usrSingle: 'usrSingle'
};
return {
    getProperty: function () {
        return vUsrProfile;
    },
    setProperty: function (value) {
        vUsrProfile = value;
    }
};
});
// angular controller
app.controller('usrPageController', function ($scope, usrTracker, conService, postService) {

var usrSingle = usrTracker.getProperty();
$scope.usrSingle = usrSingle;
$scope.cons = conService.query();
$scope.posts = postService.query();
});

(FINAL EDIT) The answer provided is a valid solution, but I opted for a different approach. I utilized the MongoDB $unwind aggregation to expand my data, as shown below.

Snippet from API file:

// retrieve data
.get(function (req, res) {
// unwind the conPlayerList array field
Con.aggregate([{ $unwind: "$conPlayerList" }], function (err, cons) {
return res.json(cons);
});
})

I then applied a filter based on the specific user I was searching for. Adjusting the Angular HTML markup as follows:

ng-repeat="con in cons | filter:{conPlayerList:usrSingle.username}"

For better example matching, a generic version would be:

ng-repeat="con in cons | filter: {y:'3'} "

Answer №1

If you want to filter an array using Angular's built-in logic, you can do so by utilizing the filter functionality. However, keep in mind that this method may not provide an exact match and could match against an array entry of 300 if the variable usrSingle is set to 3. Check out an example in this Fiddle.

<div ng-repeat = "con in cons | filter:{y:usrSingle} ">...</div> 

If you want to match exactly against array elements, you can use the filter: along with a predicate function in the controller code, like this:

Controller (Fiddle):

app.controller('usrPageController', function ($scope) {
  $scope.filterFn = filterFn;
  $scope.usrSingle = 3;
  $scope.cons = [
      {x:0, y:[1,2,3]},
      {x:1, y:[2,3,4]},
      {x:2, y:[3,4,5]},
      {x:3, y:[4,5,6]},
      {x:4, y:[5,6,7]}
  ];

  function filterFn(con){
    return con.y.indexOf($scope.usrSingle) > -1;
  }
});

View:

<div ng-repeat = "con in cons | filter:filterFn">...</div>

Another approach is to create a custom filter that can be reused in the application and pass usrSingle as a parameter:

Custom Filter (Fiddle):

app.filter('customFilter', function() {
  return function(input, value) {
    var result = [];
    input.forEach(function(item){
        if(item.y.indexOf(value) > -1){
            result.push(item);
        }
    });
    return result;
  };
});

View:

<div ng-repeat = "con in cons | customFilter:usrSingle">...</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

Using jQuery to reset the position of animated divs

I am currently working on a code that expands and centers a div when hovered upon using the following script: $(document).ready(function(){ //animation on hover $('#sliding_grid li').hover(function() { ...

Finding the attribute value within a nested array of objects retrieved from an API response

Imagine a scenario where I possess an array of unclassified objects, each of which contains an array of labeled objects: [{id: 123, name: 'Foo', code: 'ABC123', enabled: true},{id: 124, name: 'Bar', code: '123ABC', e ...

Capturing Click Events from Elements Below: A Step-by-Step Guide

In my layout, I positioned two tables side by side. Each table contains clickable items. By adjusting the margins and using relative positioning, I successfully moved the second table to be below the first one. However, a problem arose where clicking on it ...

Channeling requests from webpack dev server to .net MVC website

I am working on incorporating Vue into my .net MVC project. After installing Vue using the CLI, I included the following vue.config.js: module.exports = { devServer: { proxy: { '/': { target: 'http://mvcsite.local', ...

Guide on how to implement a file upload feature using only JavaScript and the FileReader API

Allow me to explain the issue I'm facing. To give you some context, I've been working on a forum web application. Lately, I've been trying to enable users to choose a photo from their local file system during sign up. The idea is that once a ...

Using JavaScript/Angular to borrow a function and add additional parameters

In my scenario, I have a service function that requires a static parameter and a second custom parameter that changes based on the controller it is being used in. I am looking for a way for my controller/view to invoke this service function without havin ...

Changing states in Ionic Nav View triggers a controller change, however, the view remains the same

Having some trouble with routing in Ionic and Ui-Router. I'm noticing that when I click on the link to change the view (using an anchor tag with ui-sref), the controller changes as expected (I can see output in the console), but the view remains uncha ...

Once the PostgreSQL container is stopped with docker-compose down, the previously used port becomes unavailable for use again

Currently, I am involved in a project which utilizes express as the server and postgres as the database to delve into dockerization. The server relies on the database being operational. Initially, when running docker-compose up everything functions correct ...

What strategies can I employ to optimize this code in RXJS and Angular?

Is it possible to streamline these nested arrays for more efficient execution after all subscriptions have been completed? I believe there may be a solution involving the use of pipes, mergeMaps, concatMaps, etc. this.teams = [ { Assignments: [{Id: ...

Creating an Account with Firebase

I've created a function called signup in my web project that uses JavaScript to add a user to my Firebase database. The function works fine, but I'm encountering an issue when I try to redirect to another page at the end of the function - the use ...

Struggling to comprehend the node.js walker concept

I am struggling to grasp the concept of how the signature/header of the node.js walker functions. I understand that a walker can go through a directory and apply filters, but I'm unsure about how the signature of the .on function works. For example: ...

Testing the validity of a login token in a software system

Currently, I am in the process of implementing unit testing for my application framework and so far, everything is progressing smoothly. However, I have encountered a challenge while trying to test whether the token has expired or is still active. I manag ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

Utilize Jquery to send a preset value through an ajax request

I am working on a select box functionality where the selected option is sent via ajax to a server-side script. The current setup is functioning properly. Here is the code for the select box: <select id="main_select"> <option selecte ...

Utilizing request-promise for intertwined asynchronous requests

Currently, I am utilizing the Visual Studio Online API to retrieve branch statistics by repository. To achieve this, I have incorporated nested asynchronous calls. My choice of resolving GET requests is through using request-promise. The challenge I am en ...

Troubleshooting why "ng-check="true" isn't functioning properly after radio choices update

Three columns of radio drop down boxes are present. When a user selects a radio button in the first column, the radio buttons in the second column refresh with a new list. The default behavior is for the top radio button all to be checked each time a new l ...

The index-hml-webpack-plugin is throwing an error: EISDIR - attempting to read from a directory, which is an illegal

the issue arises with the index-html-webpack-plugin plugin Despite numerous attempts to update my code and configuration, I have been unsuccessful in addressing this error. Any assistance in resolving this matter would be greatly appreciated. Thank you in ...

Please make sure to utilize messageCreate instead of the deprecated message event

Hey there, I'm currently in the process of upgrading my discord bot from v12 to v13. The bot is up and running, all commands are loaded in the console, but I'm facing an issue where a notification keeps popping up at the bottom and none of my com ...

Using jQuery to compel a user to choose a value from the autocomplete suggestions within a textarea

Currently, I have implemented a snippet that allows the user to choose cities from a list and insert them into a textarea separated by commas. However, I am looking to enhance this feature. I want the user to be able to search for a city by typing a part ...

Accelerate the window.onload process

As a newcomer to javascript and Jquery, I am working with javascript code that generates a table of content based on <h2> and <h3> tags. However, I have noticed that it is running slow as it waits for the entire page to render. I attempted to ...