Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books:

$scope.data = [{
    "title": "Alice in wonderland",
    "author": "Lewis Carroll",
    "lang": ["en"]
}, {
    "title": "Journey to the West",
    "author": "Wu Cheng'en",
    "lang": ["ch"]
}]

If we only wanted to display English books using a filter in ng-repeat, is it feasible?

For instance:

<div ng-repeat="d in data | filter:d.lang='en'" style="margin-bottom: 2%">
    {{d.title}}
</div>

The objective is to achieve this without using any form control like radio buttons. Can this be done?

-EDIT- Thanks @GrizzlyMcBear for pointing me in the right direction! I managed to make it work by using a slightly modified filter function (provided below)

app.filter('MyFilter', function() {

    var out = [];
    angular.forEach(input, function(i) {

      if (i.lang[0] === 'en') {
        out.push(i);
      }
    })

    return out;
  }

});

And in the HTML:

<div ng-repeat="d in data | MyFilter" style="margin-bottom: 2%">
    {{d.title}}
</div>

Answer №1

Give this a try

<div ng-repeat="item in items | filter: { category : 'food'} " style="margin-bottom: 2%">

DEMO

Answer №2

If you want to enhance your data filtering capabilities in Angular, try using the filter feature.

A useful tip is to implement a custom filtering function like this:

<div ng-repeat="item in collection | filter:filteringFunction" style="margin-bottom: 2%">
    {{d.title}}
</div>

This method provides flexibility in creating intricate filtering logic for your data.

var filteredLang = "en";

function filterByBookLanguage(collectionItem) {
    var result = false;

    if (collectionItem.lang[0] === filteredLang) {
        result = true;
    }

    return result;
}

$scope.filteringFunction = filterByBookLanguage;

You can easily modify the comparator function (filterByBookLanguage) as needed.

For example, if your boss suddenly wants to switch from filtering books to filtering by author name, just add this condition:

if (bossWantsToChangeFilter) {
    $scope.filteringFunction = filterByAuthorName;
} else {
    $scope.filteringFunction = filterByBookLanguage;
}

Remember to update the comparator function with the appropriate arguments and values based on your requirements.

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

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

Having trouble connecting to the webserver? Make sure the web server is up and running, and that incoming HTTP requests are not being blocked by a firewall

While working on my Visual Studio 2013 Asp.Net web code using the Local IIS Web server Version 7 (Windows 7 x64) and Framework 4.0, I encountered an error message stating: "Unable to start debugging on the web server. Unable to connect to the webserver. V ...

Altering the color upon repetition and utilizing JQuery coordinates for the dynamic movement of elements

I've been working on recreating some JQuery tutorials by myself, but I've hit a roadblock. My goal is to create an object that moves from one position to another while changing color when it repeats. I attempted to achieve this by using an array ...

A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component - data: () => ({ email: "", showError : false }), Below is the corresponding HTML code - <div v-show='showError' c ...

CoffeeScript is failing to run the code

I'm attempting to use a click function to alter the CSS code and then run a function. Here is my current code: ready: -> $("#titleDD").click -> $("#titleDD").css('text-decoration', 'underline'); $("#catDD").css( ...

Concealing objects identified by a specific id

I have two separate div elements var promptContent = $('<div id="errorr">').addClass("formErrorContent").html(promptText).appendTo(prompt); var arrow = $('<div id="errorrarrow">').addClass("formErrorArrow"); I need to refe ...

A step-by-step guide on how to repeatedly reload a nextJS page using recursion and display an error page once the

I've been experimenting with a recursive page reload function that looks like this: export const refreshPage = (count)=>{ if (count <= 0){ // window.location.reload(); console.log("blue"); return }else { console.log(& ...

Use React to increment a variable by a random value until it reaches a specific threshold

I am currently working on creating a simulated loading bar, similar to the one seen on YouTube videos. My goal is for it to last 1.5 seconds, which is the average time it takes for my page to load. However, I have encountered an issue with the following co ...

Prevent the browser from autofilling password information in a React Material UI textfield when it is in focus

I am currently utilizing React Material UI 4 and I am looking to disable the browser autofill/auto complete suggestion when focusing on my password field generated from `TextField`. Although it works for username and email, I am encountering issues with d ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Is there a way to initiate a jquery function upon loading the page, while ensuring its continued user interaction?

On my webpage, there is a JavaScript function using jQuery that I want to automatically start when the page loads. At the same time, I want to ensure that users can still interact with this function. This particular function involves selecting a link tha ...

Activate the class using Vue with the v-for directive

I'm curious about the v-for functionality. Why is it necessary to use this.activeClass = {...this.activeClass} to update the component? I noticed that the component does not update after this line of code. if (this.activeClass[index]) { ...

Display the text from a function in an imported component using React

Attempting to break down HTML chunks into smaller pieces stored in the components folder. (Note: the HTML is actually written in JSX). The goal is to import the [Navigation] component and have it display its content. I am aware that there are tools avail ...

Using jquery to update a link when a different link is clicked

Recently, I've started using JQuery and encountered a challenge. When I click on the first link, an Ajax request is sent to the server and data is received successfully. However, in the callback function, I'm struggling to change the display text ...

Best practice for integrating Typescript into an established ASP.NET 4 Webforms project

Currently, I am working on an older asp.net 4.0 Webforms project using Visual Studio 2015. My goal is to transition from using Javascript to TypeScript for certain client side code tasks. While I have experience using TypeScript in projects outside of Vis ...

How to animate a left border shifting to the center using JavaScript

As I'm modifying my current div, I need to add a vertical line in the center of it. I've come across various solutions where a left border is added and then shifted using the left property by 50% (which effectively places it in the middle). Here ...

Bringing in functions - NodeJS - non-HTML

Currently, I am in the process of learning automation for my job and have hit a roadblock. In times like these, stackoverflow has proven to be a life-saving resource :) My current task involves writing a Selenium test in VisualStudio using JavaScript (nod ...

Unable to locate the AngularJS controller after attempting to paste the code

Currently enrolled in the AngularJS Mastery Course on Udemy, I encountered an odd issue that has left me scratching my head. The code provided seems to function flawlessly for most users, except for a select few. index.html <html lang="en" ng-app=&apo ...

Step-by-step guide on incorporating a hyperlink within a row using @material-ui/data-grid

I am currently using @material-ui/data-grid to showcase some data on my webpage. Each row in the grid must have a link that leads to the next page when clicked. I have all the necessary data ready to be passed, however, I am facing difficulty in creating a ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...