Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'}

html

 <div class="variable" ng-repeat="item in items">{{item}} </div>

I am looking to achieve the following:

If the item is apple, banana, lemon, then the variable should be fruit.

If the item is cat, dog, monkey, then the variable should be animal.

If the item is tom, john, baby, then the variable should be human.

Fruit, animal, human are CSS classes.

Your assistance would be greatly appreciated. Thank you!

Answer №1

Revise the items that are in an incorrect array format

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'}

to

items = ['apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby']

Utilizing ng-class is a recommended approach.

Example:

<div ng-repeat="item it items" ng-class="defineClass(item)">{{item}}</div>

Controller:

$scope.items = ['apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'];

$scope.defineClass = function(item) {
    switch (item) {
        case 'apple':
        case 'banana':
        case 'lemon':
            return 'fruit'; 
            break;
        case 'cat':
        case 'dog':
        case 'monkey':
            return 'animal'; 
            break;
        case 'tom':
        case 'john':
        case 'baby':
            return 'human'; 
            break;
    }
}

Answer №2

Implement ng-class for dynamic styling.

<div ng-class="{'classname':variable}" ng-repeat="item in items">{{item}} </div>

Here is a practical example:

<div ng-class="{'human':item == 'tom'}" ng-repeat="item in items">{{item}} </div>

Answer №3

controller

$scope.fruit = ['apple', 'banana', 'lemon'];
$scope.animal = ['cat', 'dog', 'monkey'];
$scope.human = ['tom', 'john', 'baby'];

$scope.items = $scope.fruit.concat($scope.animal).concat($scope.human);

$scope.checkType = function(type, item) {
    return ($scope[type].indexOf(item) != -1);
}

template

<div ng-class="{fruit: checkType('fruit',item), animal: checkType('animal',item), human: checkType('human',item)}" ng-repeat="item in items">{{item}} </div>

Answer №4

One effective strategy is to utilize a diverse data structure. Here's an example:

var items = [
    {name: 'apple', type: 'fruit'},    
    {name: 'banana', type: 'fruit'},
    {name: 'lemon', type: 'fruit'},
    {name: 'cat', type: 'animal'},
    {name: 'dog', type: 'animal'},
    {name: 'monkey', type: 'animal'},
    {name: 'tom', type: 'human'},
    {name: 'john', type: 'human'},
    {name: 'baby', type: 'human'}
];

Although more detailed, this approach offers convenience in return. When adding a new item later on, there's no need to modify the template or update controller code for support. The class name will be assigned automatically.

<div class="{{item.type}}" ng-repeat="item in items">{{item.name}}</div>

Demo: http://plnkr.co/edit/nrlSChOkp0rC7KRPI3FO?p=preview

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

What is the reason behind jshint issuing an alert specifically for the lastSelectedRow being

Upon pasting the code below into jshint.com, an error is generated: Read only in reference to line: lastSelectedRow = 1; I am curious as to why this error occurs and how it can be remedied. Interestingly, jslint does not return this error. /*global la ...

What steps should I follow to effectively store this JSONB data in PostgreSQL by utilizing node-postgres (pg)?

After receiving information in the GET URL, I need to pass it into JSON format and save it with increasing IDs into a PostgreSQL database. However, the code I wrote does not seem to be saving anything without any errors: // Initializing Pg const { Client ...

Starting service upon startup in Angularjs

I am looking to retrieve configuration data from the server and store it in the global scope within my AngularJS application. My app operates in multiple modes such as development and production, with different external services being used depending on the ...

Changes to the parent state will not be reflected in the child props

When the child component PlaylistSpotify updates the state localPlaylist of its parent, I encounter an issue where the props in PlaylistSpotify do not update with the new results. I've been struggling to figure out what I'm missing or doing wrong ...

WordPress now features the ability to toggle both parent menu items when clicked, providing a more streamlined user experience

I am currently facing an issue with a menu structure, where parent menu items have submenus that need to toggle on click. However, I am encountering a problem where, upon placing the code inside a forEach loop, both submenus toggle instead of only togglin ...

Is verifying email and password with jquery possible?

I am currently working on a jQuery form validation project: While the password and username validation are working fine, I am facing issues with email and password confirmation validations. Surprisingly, I have used the same technique for both. If you wa ...

Having trouble retrieving data from the server for the POST request

I am fairly new to using Jquery and Ajax requests. I'm currently working on a website where I have a simple form that collects an email address from users and sends it to the server. However, I'm struggling to figure out how to capture the form d ...

What is the best way to execute a function every 10 seconds?

Is there a way to continuously call a function every 10 seconds? Currently, using $timeout and setTimeout only triggers the function dataTime once. I need it to repeat indefinitely. angular .module('sfcLeftSiteBar') .component('leftSiteBar ...

Why is useEffect being executed twice?

For some reason, when I try to run useEffect for the first time page load, it ends up running twice. I can't seem to figure out why this is happening. Can someone please provide assistance? I'm currently using React 18 and I need help understand ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

A guide on activating dropdown buttons individually using AngularJS (Cascading dropdowns)

When it comes to cascading dropdowns (for example: with 3 dropdowns), the challenge is to disable the 2nd and 3rd dropdown initially. Only when a user selects an option in the 1st dropdown, should the 2nd dropdown be enabled. Similarly, once an option is s ...

Validation customized through offspring control

Currently, I am dealing with a situation where I need to transclude all controls within a directive that has its own form element and buttons. The model in this context includes a property for the total capacity and another property that consists of compar ...

Refresh the table dynamically in Django without the need to reload the entire page

Seeking assistance to update a small table with new data every 10 seconds on a Django website. The data is parsed into JSON and refreshed in the database, then displayed on the front-end. Looking for help with writing AJAX code to continuously refresh the ...

Re-activate external script following a language update in Next.js

In my Next.js 13 app, I have implemented a live chat support button that is dynamically added based on the language selection. The code for rendering the button looks like this: import Script from 'next/script'; ... <div id={`onlinehelp-button ...

Adding custom styles to Material-UI components

` import React, { Component } from 'react'; import Header from './Components/UI/header'; import { Box, Paper } from '@material-ui/core'; import { ThemeProvider, withStyles} from '@material-ui/core/styles'; const ...

What could be causing "Unknown property" errors when using unicode property escapes?

The MDN website provides examples of matching patterns with unicode support, such as: const sentence = 'A ticket to 大阪 costs ¥2000 ...

Start running additional JavaScript code only after the previous one has been fully executed

Scenario: I am facing a situation where I have a web form that is submitted through the following event listener: $('#myForm').on('valid', function (e) { ... } Within this function, I have a code snippet that fetches the geo location ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Changing the Title of UI Tabs

I am facing an issue with setting the title in tabs, as the title is appearing behind the background. If I set background: transparent; in the #tabss .ui-tabs-nav class, then my title shows up properly. Otherwise, it gets displayed behind the background. ...

chosen selection from AngularJS dropdown

I'm really struggling with something. Currently, I am working on a web app using AngularJS where I have created a table displaying database results. Each row in the table contains a select item loaded with a model. However, I am unsure how to mark a ...