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

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

Every time I run `npm install`, I consistently encounter the `code ECONNREFUSED` error message for every

`npm ERR! code ECONNREFUSED npm ERR! errno ECONNREFUSED npm ERR! FetchError: request to http://registry.npmjs.org/body-parser failed, reason: connect ECONNREFUSED 127.0.0.1:3000` I attempted various solutions such as adjusting proxy settings and running ...

Centering the overlay gallery box in MonoBook Skin of MediaWiki using CSS

While working on transforming the MonoBook Skin into a DarkMode version, I encountered an issue with the gallery overlay css. The Overlay displays a semi-translucent white box with text at the bottom by default, overlaying the image. I made adjustments to ...

Encountering ActionController::UnknownFormat error while transferring data from an Angular application in Rails 5

Recently, I have delved into learning Angular with Rails. However, I encountered an issue when making a $http.get() request - it keeps returning an error. I suspect that Rails may be rejecting the data. Here is the snippet of my code: View: <div clas ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

Tips for maintaining an updated array's consistency on page refresh in Vue.js?

HelloWorld.vue Dynamic routing in Vuejs: <template> <div> <b>Vuejs dynamic routing</b> <div v-for="item in items" :key="item.id"> <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp; <rou ...

CKEditor with Readonly Option and Active Toolbar Controls

In my current Rails project, I have successfully set up a CKEditor instance in readOnly mode. Everything is functioning as expected. Now, I am attempting to add a custom plugin button to the toolbar while keeping the textarea in readOnly mode. After some ...

Tips for utilizing the data-target feature in Bootstrap?

<button id="btn-id" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#bs-navbar-collapse-1"> <span class="navbar-toggler-icon"></span> <span c ...

What causes the navbar-brand to be hidden on Chrome mobile browsers?

I recently completed building my website at emdashr.com and have been adjusting the mobile views. However, I'm facing an issue where the navbar-brand disappears when viewing the site on mobile Chrome or desktop Chrome with a small viewport. Interestin ...

The art of connecting Javascript commands in succession

I'm struggling to grasp the concept of chaining and return in JavaScript. For example, consider the following code snippet: let array = [1, 2, 3] let newArray = array.map(val => val * 10).map(val => val * 10) console.log(newArray) // [100, 200, ...

How can I ensure my card div is responsive in Bootstrap?

My current section consists of only 6 cards, with 3 cards in a row of 2. When the screen size reduces (to mobile phone size), I want each card to be on its own row, displaying one by one as the user scrolls. Although it functions as desired when I resize ...

Integrating jQuery Tooltip with Mouseover Event

I'm currently involved in creating a map of MIT projects for an architectural firm, and facing the challenge of maintaining the red dots mouseover state even when the mouse hovers over the tooltips that appear. Presently, the mouseover effect turns of ...

The fetch() POST request is met with an error message stating "415 Unsupported Media Type"

I keep encountering a 415 error when attempting to upload a PDF file using fetch(). The PDF file resides in the same directory as the js file, and the name is correct. async function uploadFile(filePath, extension, timestamp) { const url = "https ...

Adjust the object's width and position based on the window's width

I am currently attempting to adjust the width of a box and the position of a btn based on the size of the window. Q1. How can I eliminate the excess white space located behind the scroll bar? (I have already set it to 100%..) Q2. After clicking the ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

Components for managing Create, Read, Update, and Delete operations

As I embark on my Angular 2 journey with TypeScript, I am exploring the most efficient way to structure my application. Consider a scenario where I need to perform CRUD operations on a product. Should I create a separate component for each operation, such ...

Transparent dropdown elements using Bootstrap

I'm trying to incorporate a transparent bootstrap dropdown into my form. Specifically, I want the button itself to be transparent, not the dropdown list that appears when the button is clicked. Here's an example of what I currently have: https: ...

Omit the <span> tag when exporting to XLS format

Currently, I have a functioning jQuery DataTable that utilizes the TableTools plug-in and includes <span> elements in one of the columns for each row. When clicking on the export button, my goal is to exclude or hide the <span> elements from t ...

Unpacking objects within an array in the backend of a Next.js application

How can I resolve this issue? I am passing the req.query parameter with an array but I am unable to destructure or use items from the array. In my Next.js API backend, I only get [object Object] or undefined. How can I access and select specific values fro ...