Use ng-class based on a condition

In my current project, I have a requirement to display different images based on certain conditions. For example, if condition1 is met, I need to show image1, and so on for other conditions. To achieve this, I am currently using the ng-if directive in my code like below:

<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left"
     ng-if="data.severity==3">
        <img src="App/images/Icons/alarm-high.png">
</div>
<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left"
     ng-if="data.severity==2">
        <img src="App/images/Icons/alarm-medium.png">
</div>
<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left"
     ng-if="data.severity==1">
        <img src="App/images/Icons/alarm-low.png">
</div>

Although I only need to display one image at a time, I find myself repeating similar lines of code multiple times. Is there a way to optimize this using the ng-class directive instead?

Answer №1

An alternative approach is to utilize ng-switch directive:

<span ng-switch on="data.severity">
   <img ng-switch-when="1" src='App/images/Icons/alarm-low.png'>
   <img ng-switch-when="2" src='App/images/Icons/alarm-medium.png'>
   <img ng-switch-when="3" src='App/images/Icons/alarm-high.png'>
   <img ng-switch-default   src='default image source'>
</span>

Answer №2

By utilizing ng-src, you can dynamically alter the image source with just one line of code :)

<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left"> 
    <img ng-src="{{img.src}}"> 
</div>

Within the Controller:

if($scope.data.severity == 2){
    $scope.img.src = 'App/images/Icons/alarm-medium.png';
} else if($scope.data.severity==1){
    $scope.img.src = 'App/images/Icons/alarm-low.png';
}

UPDATE

It has been noted in the comments that this approach may not work if utilized multiple times on a single page. Therefore, an alternative solution is provided below.

<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left"> 
    <img ng-src="{{ getSeverity(data.severity) }}"> 
</div>

-

$scope.getSeverity = function(severity){
    if(severity == 2){
         return 'App/images/Icons/alarm-medium.png';
    } else if(severity == 1){
         return 'App/images/Icons/alarm-low.png';
    }
}

-

In regards to your bootstrap code, consider simplifying by removing unnecessary classes from the div, such as col-sm-1 and above. The col-xs-1 will suffice for all screen sizes.

<div class="col-xs-1 form-col-pad customization-grid-data text-left"> 

Answer №3

Learn HTML

<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left">
        <img ng-src="{{'App/images/Icons/alarm-' + (data.severity == 1 ? 'low' : (data.severity == 2 ? 'medium' : 'high')) + '.png'}}">
</div>

OR

Master JavaScript

<div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 form-col-pad customization-grid-data text-left">
        <img ng-src="{{getSeveritySrc(data)}}">
</div>

Coding in Controller

$scope.getSeveritySrc = function(data){
    var src = 'App/images/Icons/alarm-';
    switch(data.severity){
        case 1:
            src += 'low';
        break;
        case 2:
            src += 'medium';
        break;
        default:
            src += 'high';
        break;
    }
    src += '.png';
    return src;
}

OR

Styling with CSS

ng-class="{'low':data.severity == 1,'medium':data.severity == 2,'high':data.severity == 3}"

Example Design with CSS

.low {
    background: green;
}

.medium {
    background: yellow;
}

.high {
    background: red;
}

OR

Enhance HTML Attributes

ng-class="getSeverityClass(data)"

Advanced Functions in Controller

$scope.getSeverityClass = function(data){
    switch(data.severity){
        case 1:
            return 'low';
        break;
        case 2:
            return 'medium';
        break;
        default:
            return 'high';
        break;
    } 
}

Visit this JSFiddle link for a demonstration.

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

Top tips for maintaining timer functionality in a Progressive Web App

I'm in the process of developing a progressive web app with React that centers around maintaining a running timer. Just to provide some background, this app is designed for home-brewers who want to keep track of when certain ingredients like hops n ...

Having difficulty accessing the uploaded file through the <input type="file"> feature

I need help with uploading a file using the input type="file" and then sending it via email along with other data. However, when I receive the email, I can see all the text data but not the uploaded file. The file path displayed is something like "C:\ ...

What is the best way to add <li> to every element in an array?

I had a tough day today trying to figure out my code. My English isn't the best, so explaining my issue is hard. I decided to illustrate my problem in HTML and specify the kind of styling I need to achieve with JS. I also included an example using the ...

What are the steps to utilize the Angular package within NodeJS and Express?

After installing the Angular package through npm install for my Express project, I am feeling a bit lost on how to actually use it. Can someone explain how to properly implement Angular after installing it this way? Alternatively, is the only way to util ...

HTML5 Video validation is not working properly

In my current project, I initially used embedded Youtube videos but faced issues with validation. Decided to explore HTML5 video elements as an alternative, but encountered some challenges. While attempting to validate the code, strange errors popped up: ...

Trouble with jQuery click event on dynamically generated elements

I have a jQuery function that iterates through each element inside a specified div (#container) and triggers a JavaScript alert whenever a span is clicked. Everything functions correctly when the spans are static. However, when I include code like this: ...

Is there a way to deactivate the minutes input feature in the Angular UI Timepicker?

I am using a plugin that displays the time in hours and minutes. However, I only need to show the hours. Is there a way to hide the minutes block? This is my HTML code: <uib-timepicker ng-model="mytime" ng-change="changed()" hour-step="1" minute-step ...

Unable to apply border-radius to a specific HTML table

I am facing an issue where the border-radius is not being displayed on a specific HTML table. I am having difficulty in applying rounded corners to the entire table so that the table edges have a 30px curve. Here is an example of what I am looking for: ht ...

Incorporating tawk.to into a Nuxt/Vue application

Has anyone had success implementing tawk.to in a Nuxt application? I took the initiative to create a file called "tawk.js" in my plugin folder and added the following code: var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date() (function () { ...

The initialization of Angular forms containing dynamic names is not occurring as expected

I am facing a challenge where I have multiple objects and a form associated with each object that needs to remember its state, particularly if it's dirty. My goal is to create a form with a dynamic name structure like this: <form name="selectedO ...

Develop a voice recording feature using ReactJS

In my quest to enhance a chat application with voice recording functionality, I came across the react-mic package. It worked smoothly and provided me with the data needed at the end of the recording session. (link: https://i.stack.imgur.com/nhNCq.png) Now ...

Turn off smooth scrolling in Bootstrap 5 using HTML and CSS techniques

On my website, I have implemented anchor links that activate smooth scrolling when clicked, thanks to the Bootstrap feature. However, the unique layout of my website requires me to turn off smooth scrolling in either the HTML or CSS code. I appreciate an ...

Adhesive Bottom Navigation, Top Banner, and Full-Height Page Content

Trying to create a header, sticky footer, and content section with 100% height, but facing issues with the middle height. Below is the code and jsfiddles provided. Using HTML 4.0 strict in IE7 without the option to change. jsfiddle without 100% height: ht ...

Arranging an array based on various conditions and criteria

I am struggling to incorporate sorting and ordering into an array. The obstacle I am encountering involves having 5 criteria for sorting, which are: due_date === 1000 status && is_approved(boolean) is_overdue(boolean checking with date-fns using ...

How can Vue.js implement a satisfactory method for synchronizing computed values with asynchronous data?

Imagine retrieving a list of products from the state manager in your Vue.js component, where a computed property is then used to process this list for display on the DOM. <template> <span>{{ computedProducts }}</span> </template> ...

[Vue alert]: Issue encountered with intersect unbind hook in directive: "TypeError: Cannot access 'observer' property of undefined"

I'm puzzled by the appearance of this message. It only shows up when I click on a button and get redirected to the page using router.push. [Vue warn]: Error in directive intersect unbind hook: "TypeError: Cannot read property 'observer&apos ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

Utilizing Selenium and Protractor for efficient text entry with the ng-model locator

I am using Selenium and Protractor to input text into text fields located by Angular locators. However, after I enter the text, the field does not immediately display the entered text until I click on it again. Essentially, it is not dynamically refreshin ...

Issues with compatibility between camera slider and nivo lightbox in jQuery

Encountering a problem with using slider and nivo lightbox together in one PHP file. Here is the code snippet: <script type="text/javascript" src="js/slider/jquerySlider.min.js"></script> <script type="text/javascript" src="js/slider/jq ...

Difficulty with implementing authentication middleware based on a condition in Express using Node.js

Currently in the process of developing my website, which includes utilizing an API built with node.js, express, and MongoDb for the database. I am facing a challenge with creating a middleware to ensure that the USER ID matches the POSTED BY ID in a COMME ...