Determine the presence of an object within an array and apply an ng-class to it using AngularJS

Check out this Plunker for live demo: https://plnkr.co/edit/SRjkoo2mi5C2P1dVsYST?p=preview

We have a total of 3 fruits:


$scope.fruits = [{
    _id: "3",
    name: "apple"
}, {
    _id: "4",
    name: "orange"
}, {
    _id: "5",
    name: "banana"
}];

and there are 2 different shops:


$scope.shops = [{
    name: "Tesco",
    _id: "1",
    fruits: [{
        _id: "3",
        name: "apple"
    }]
},{
    name: "Waitrose",
    _id: "2",
    fruits: [{
        _id: "4",
        name: "orange"
    }]
}];

Each shop has only 1 fruit available, as you can see above.

When displaying the available fruits for each shop in the view, we want to highlight them in red by adding the "class-1" class.

The current code snippet provided below is not functioning as expected:


<div ng-repeat="shop in shops">
  <div>{{shop.name}}</div>
  <div ng-repeat="fruit in fruits" ng-class="shop.fruits.indexOf(fruit._id) !== -1 ? 'class-1' : 'class-2'">{{fruit}}</div>
</div>

(Referenced from this helpful answer: How to check if something is in array from ng-class)

Answer №1

Each shop is limited to only one type of fruit, so the syntax would be as follows:

 <div ng-class="shop.fruits[0].id.indexOf(fruit._id) === -1 ? 'class-1' : 'class-2'">{{fruit}}</div>

Visit this link for more details.

Check out the updated plnkr at: https://plnkr.co/edit/cnzjGWSIT86Q2VYa6aSM?p=preview

Here is the HTML code snippet:

 <div ng-repeat="fruit in fruits" ng-class="checkFruit(shop, fruit) ? 'class-1' : 'class-2'">{{fruit}}</div>

And here is the JavaScript logic:

$scope.checkFruit = function(shop, oneFruit) {

for(var i = 0, m = shop.fruits.length; i < m; i++) {
  if(shop.fruits[i]._id === oneFruit._id) {
    return true;
  }
}
return false;

}

You also have the option to simplify the checkFruit function using underscoreJS.

Answer №2

Although I don't have much experience with Angular, do you think something like this could work?

<div ng-class="shop.fruits.find(sf => sf._id === fruit._id) ? 'class-1' : 'class-2'">{{fruit}}</div>

Answer №3

To customize each shop-related div, you have the option to assign a unique class name. This allows for targeted styling using CSS:

.shop-1 .fruit-item {background: red;}

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

When using react, it is not possible to have a <span> element as a child of a <

I designed a custom select dropdown feature for use in a redux-form within a react-redux application. The dropdown functions well, with no performance issues, but I am encountering a warning in the browser. Warning: validateDOMNesting(...): <span> c ...

custom checkbox is not being marked as checked

I've been attempting to customize my checkboxes, following various tutorials without success. Despite trying multiple methods, I still can't get the checkboxes to check or uncheck. Here is the code I have so far: https://jsfiddle.net/NecroSyri/ ...

Combining inheritance and isolated scopes: a comprehensive guide

I've encountered a situation where I need to sort an HTML table. Here is the code snippet: <table> <thead> <tr> <th custom-sort-one order="'Name'" >Name</th> </ ...

Clicking on the button will instantly relocate the dynamically generated content to the top of the page, thanks to Vue

Here is some dynamically generated content in the left column: <div v-for="index in total" :key="index"> <h2>Dynamic content: <span v-text="index + ' of ' + total"></span></h2> </div> There is also a butt ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Unusual conduct when employing basic directive for validation messages

Within my code, I have implemented the following directive: App.directive("validateMsgFor", function(){ return{ templateUrl : "view/templates/validateMsgFor.html", restrict: "E", scope: { field : "=" } ...

Error occurs when using Vue 3 Transition component with a child <slot> tag

I have developed a unique component that enables me to incorporate a smooth fading transition without the need to repeatedly use the <transition> element: <transition mode="out-in" enter-active-class="transition- ...

Is it possible to use HTML text as a CSS selector with JavaScript?

I've been searching for a solution to this issue but haven't found anything that works for me. Check out this code on jsfiddle. Person1 and Person2 both have class="from" and the CSS selector is .from so it applies to both. However, I want it ...

Unusual clash between ngAnimate and ngRoute

There seems to be an unusual issue occurring between ngAnimate and ngRoute that I have noticed. Whenever I attempt to reload the current route without refreshing the entire page, something goes awry and my leaflet map fails to reinitialize. To illustrate t ...

When using a Kendo Grid with a Checkbox as a column, the focus automatically shifts to the first

Whenever I select a checkbox in my Kendo grid, the focus automatically shifts to the first cell of the first row. How can I prevent this from happening? Here is the code I am currently using when a checkbox is checked: $('#approvaltranslistview' ...

Is there any npm module available that can generate user-friendly unique identifiers?

Struggling to come across a user-friendly and easily readable unique ID generator for storing orders in my backend system. I have considered using the timestamp method, but it seems too lengthy based on my research. ...

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

AngularJS Chrome Extension has been flagged as potentially harmful, despite the implementation of compileProvider.aHrefSanitizationWhitelist. This has resulted

I have previously shared this issue, however, the suggested solutions did not resolve it. Therefore, I am reposting with a more widely recognized solution: I am currently working on developing a chrome extension using AngularJS. In my base directive, I am ...

How can global variables be effectively shared and edited between two separate runs of JavaScript nodes?

The primary function contained in main.js is as follows: var nLastPingTime = 0, nLastPingNumber = 0; module.exports = { compareData: function(nPingTime, nLastPingNumber){ nLastPingTime = nPingTime; nLastPingNumber = nLastPi ...

Modifying icons with JavaScript

When I click on the play icon, it changes to the pause icon. However, I am only able to change the first icon from play to pause in my JavaScript code. How can I apply this functionality to all the audio elements on the page? let playIcon = "https://ima ...

Error encountered: Unexpected identifier in Reactjs code

I created a new application using create-react-app and encountered an Uncaught SyntaxError: Unexpected identifier for this particular line: import React, { Component } from 'react'; within the file public/scripts/app.js: 'use strict' ...

Loop through the JSON array and append every value to the list within AngularJS

I'm just starting to learn about Angular JS and I have a question. I receive a JSON array as an AJAX response from a PHP page. I want to iterate through this JSON array and push each value into a list like this: angular.forEach($scope.companies.area, ...

Changing the structure of elements in an array using JavaScript

I am seeking a way to convert an array of strings, which represent dates in the format of 201001 ,201002, into something more readable like 2010 January, 2010 February. Do you have any suggestions on how to achieve this? var Array = ["201005", "201006", " ...

AJAX: The form submission without refreshing the page only functions for the first attempt

My current issue involves using AJAX to submit a form without refreshing the page. The problem arises when I try to submit the form more than once, as the on('submit') function stops working after the initial submission. This defeats the purpose ...

Assistance is required to navigate my character within the canvas

Having trouble getting the image to move in the canvas. Have tried multiple methods with no success. Please assist! var canvas = document.getElementById("mainCanvas"); canvas.width = document.body.clientWidth; canvas.height = document.body.clientHeight; ...