using numerous if statements in ng-class

In my AngularJS application, I have a piece of code that I'm using in a table. I want to apply the 'rare' class only to rows with an index of 0, 1, or 2. In other words, I want to highlight the first three rows differently from the rest.

Currently, I have the following code snippet:

ng-class="{rare : $index === 0, rare : $index === 1, rare : $index === 2}"

However, I'm wondering if there is a simpler or more concise way to achieve this. Is my current solution considered good practice? Although it works, I find the syntax a bit cumbersome. How would you approach writing the conditional checks in a clearer manner?

I attempted the following alternative:

ng-class="{rare : $index === {0,1,2}}
, but unfortunately, it did not work as expected.

Answer №1

To handle a list of values, you can utilize the following approach.

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.data = "Test";
    $scope.rareList = [1, 2, 3];
    $scope.val1 = 2;
    $scope.val2 = 5;
  }
]);
.active {
  color: red;
}
.not-active {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div ng-class="rareList.includes(val1)? 'active' : 'not-active'">{{data}}</div>
    <div ng-class="rareList.includes(val2)? 'active' : 'not-active'">{{data}}</div>
  </div>
</div>

Answer №2

It seems like a common mistake to overlook the fact that $index, as the row index, always starts at 0 and then increments. Therefore, you can ignore the lower limit and simply check if the index is less than the upper limit (remember that $index is zero-indexed unless explicitly set otherwise, so checking if it's less than three will include row indexes 0, 1, and 2).

ng-class="{rare: $index < 3}"

var app = angular.module("sampleApp", []);

    app.controller("sampleController", ["$scope",
      function($scope) {
        $scope.data = ['test1','test2','test3','test4'];
      }
    ]);
.rare {
    color: red;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
    <div ng-app="sampleApp">
      <div ng-controller="sampleController">
        <div ng-class="{rare: $index < 3}" ng-repeat="datum in data">{{datum}} ($index = {{$index}})</div>

      </div>
    </div>

Answer №3

Consideration:

ng-class="{special : [0,1,2].indexOf($index) >= 0}}

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 trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Mentioning Nodejs' process.argv unexpectedly triggers errors when reading a file

I am currently working on a code that is responsible for generating a very large JSON object, saving it to a file, and then loading the file to insert the data into a Mongo collection. My goal is to pass a string from the command line when executing the sc ...

Angular Persistent States in Angular version 2 and beyond

Currently, I am in the process of transitioning an Angular 1.5.X application to Angular 4. Within my app, I incorporate Angular Ui-Router Sticky State from https://github.com/ui-router/sticky-states to prevent loss of content within my view when navigating ...

Module Express - Transferring Object to Main Application

Having issues with passing an object in Express from a module to my application. The process is straightforward - gathering input from a form, validating the string, and returning either null or an object. Despite trying various methods, I'm still fac ...

Ways to ensure a button is ready to be clicked

For my beginner chrome extension project, I am facing a specific situation that I need help with. Imagine a scenario where I have a website with a search button. When the button is clicked, two possibilities can arise: A search result appears with a butt ...

Parsing JSON stored in local storage and converting it to a Fabric JS object - JSON generated from form inputs

Currently, I am facing some challenges while using Fabric js for a project that I am working on. My main goal is to create a form where users can input details, which will then be converted into a JSON object and stored locally. After submitting the form, ...

The conversion of a 2D json array into a string is mistakenly performed

On hand is an outer array that contains 2 arrays within it, making it a 2-dimensional array. This is how the array is initialized: $outerArray = array(); $nestedArray = array("first", "second", "third", "fourth"); $outerArray[] = $nestedArray; $nest ...

The dynamic form is programmed to display identical values for both the initial and subsequent inputs

Currently, I am developing a personalized dynamic form utilizing the Material UI library as the component for my React Js application. You can find more information about this library at https://mui.com/. In front of you is the initial setup of the dynami ...

Detecting a Checkbox Click Event in JavaScript

I am working with a table that has the following structure: <tbody id="ggwp"> <tr class="r123 disable-it"> <td> <input type="checkbox" name="item" class="row" statusid="1234"> </td> </ ...

Issue with a variable within an *.ejs file

Currently, I am following a guide found at this link, and everything is working smoothly except when I encounter an error on the login screen: ..... 7| >> 8| <% if (message != null) { %> 9| <%= message %> 10| <% } %> 11| message ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Getting access to the useState values within the getServerSideProps function in NextJS

How can I access the useState variable searchQuery inside the getServerSideProps function when one function takes user input and another performs a search for that input data? function SearchDemo() { const [searchQuery, setSearchQuery] = useState(&a ...

What is the proper method for incorporating a Greater-than symbol within a jsx tag?

I am attempting to display a Greater-than sign '>' inside of a button using material-ui with react, but I am receiving a parsing error. Is there a simpler way to achieve this without writing lengthy code? <Button onClick={includeOperator(& ...

Place a cookie on the alternate language domain

Within my website, we utilize 2 distinct domains, each dedicated to a different language. www.mysite.com en.mysite.com I am interested in implementing JavaScript to establish a cookie on en.mysite.com when clicking a link on www.mysite.com. Here is my ...

Having trouble making an ajax request using Cordova?

I recently started a new project and included some code for making a request. Below is how my JavaScript file looks: (function () { "use strict"; document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false ); function onDeviceR ...

Sign-in options displayed in a drop-down menu

I have successfully implemented a jQuery animation for a dropdown sign in div. The sign up form is integrated with PHP to verify the existence of users in the database. However, I came across an issue where if I echo something, the dropdown menu disappears ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Enhancing website security using Content Security Policy in conjunction with Google Closure

Implementing CSP for my web application is a top priority. Here's the policy I have in mind: "default-src 'self' gap: cdvfile;" I rely on google closure for my javascript needs. However, it seems that without javascript optimization, my ...

Retrieving the value of a radio button using jQuery and Ajax

Looking for assistance with radio buttons... <input type="radio" id="flip" name="flip" value="Head" checked="checked" /> Head <input type="radio" id="flip" name="flip" value="Tail" /> Tail I'm attempting to process a form with ajax, try ...