Employ ng-class function in Angular JS

Utilizing the ng-class feature to include CSS classes has been a bit challenging for me. Despite reading numerous articles on the topic, I am still struggling with implementing a function call within ng-class.

Below is the expression I am working with:

ng-class="{'highlighter-row-Class' : (file.id == 1 && file.processed),
    'bold-row-Class' : lastSelectedResumeId == file.attributes.name, 
    'failed-doc': !file.processed}"

While multiple classes can be added using this method, I aim to include an additional condition that triggers a method and returns a specific class name:

$scope.getclass = function() {
  return 'someclass';
}

I attempted to use this method within ng-class after the last condition, but it did not work as expected. Can someone guide me on the correct way to achieve this using ng-class?


Revised approach based on feedback:

ng-class="[{'highlighter-row-Class' : (file.id == 1 && file.processed),
    'bold-row-Class' : lastSelectedResumeId == file.attributes.name, 
    'failed-doc': !file.processed }, getClassForHrms(file)]"

Function Definition:

$scope.getClassForHrms = function (file) {
    if (file.attributes.hrmsMandatoryFieldsMissing) {
        return "missingfieldspresent";
    } else if (file.attributes.isDocumentDuplicated) {
        return "documentduplicate";
    } else if (!file.attributes.isDocumentDuplicated) {
        return "documentuploadfailed";
    }
};

CSS Used:

.missingfieldspresent {
  color: red;
}
.documentduplicate {
  color: purple;
}
.documentuploadfailed {
  color: deeppink;
}

Here's how the final HTML output appears:

<tr ng-repeat="file in processResumeFiles" ng-class="[{'highlighter-row-Class' : (file.id == 1 &amp;&amp; file.processed), 
    'bold-row-Class' : lastSelectedResumeId == file.attributes.name, 
    'failed-doc': !file.processed }, getClassForHrms(file)]" 
    class="ng-scope [object Object] documentduplicate">

Answer №1

If you require an array consisting of different classes, where one element in the array can represent classes based on certain conditions and the other triggers a function call, a basic example would look like this:

ng-class="[{'some_class' : condition}, function_class()]"

Here's a demonstration:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.bb = function() {
    return "b";
  }
});
.a {
  color: #999999;
}

.b {
  background-color: #F1F1F1;
}

.c {
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  <br><input type="checkbox" ng-model="aa" /> A: color : #999999
  <br><input type="checkbox" ng-model="cc" /> C: font-size : 30px

  <div ng-class="[ bb(), {'a':aa, 'c':cc} ]">
    <p>Testing classes</p>
  </div>

</div>


For your specific scenario, it seems like you need:

ng-class="[{'highlighter-row-Class' : (file.id == 1 && file.processed) 
        ,'bold-row-Class' : lastSelectedResumeId == file.attributes.name, 
       'failed-doc': !file.processed}, getclass()]"

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

Align the text in the center of the image, which is depicted as a bullet point

I am currently using images as bullet points for my Github Pages (markdown files), following the instructions outlined here. My goal now is to vertically center the text next to the image. This is demonstrated here (cf. lower third of page), however, I am ...

Navigating through nested JSON objects in React to display data effectively

I have been struggling for hours to find a solution to this problem with no success. I really need your assistance. The task at hand involves looping through a JSON file and creating a user interface that consists of multiple columns, each containing vari ...

Incorporating animation effects in ajax technology

I've coded a feature that utilizes the .getJSON API from jQuery to retrieve images from the Flickr public API. You can view it on this link. Each image slides after every request is completed. Now, I would like the initial set of images to slide downw ...

What is the best way to ensure that this header remains adaptable to different screen

Looking for guidance on creating a fluid and responsive header design similar to the curved images shown at this link or this link. How can I ensure that my design maintains its shape without distortion when viewed on different devices? Any suggestions a ...

Comparison: Traditional Polling vs Using hidden iFrame for Ajax history tracking

Situation Keeping track of changes in the URL hash and ensuring proper functionality for the forward/back buttons are essential tasks for libraries that manage Ajax history. There are two main approaches to implementing these libraries. One option is to h ...

Discovering the method to read a file that is currently downloading in either JavaScript or Python

Imagine a scenario where I am actively downloading a file while simultaneously wanting to read its contents. However, the file is being continuously updated during the download process. For instance, if I start reading the file when the progress bar shows ...

Retrieve active route information from another component

We are utilizing a component (ka-cockpit-panel) that is not linked to any route and manually inserted into another component like so: .. ... <section class="ka-cockpit-panel cockpit-1 pull-left"> <ka-cockpit-panel></ka- ...

Using Three.js to apply multiple images onto a sphere and have individual control over each one

I have a 3D sphere that I am looking to map an array of images onto. I want to be able to control each image independently, allowing for fading in and out of each image. To better illustrate my goal, I will provide an example image of what I am trying to a ...

Unable to decrease the width of a div element in Vuetify and Nuxt

As I work on creating a dynamic form with fields that need to occupy only 50% of the size of a regular field, I encounter different components based on data provided by Vuex. The use of v-for in Vue.js helps me loop through form objects and render the app ...

Is there a way to adjust the placement of this AccordionDetails utilizing Material UI's Grid system?

Here is a sketch of what I am aiming for: https://i.sstatic.net/SFHSpm.png This is my implementation using Material UI's Accordion component. https://i.sstatic.net/JyhCym.png Below is the code snippet for the AccordionDetails section, which is whe ...

One issue I've encountered is that Angularfire seems to have trouble reading the "facebook" property. So my question

I have been developing an android game using the ionic framework and firebase. My goal is to implement a feature where users can log in using Facebook login with Firebase, and then save the game data to the user's database key. The initial part of t ...

"Resolving the duplication issue of a textbox in Phonegap app

I encountered a strange issue recently. While trying to focus on the textbox in my PhoneGap application using touch, I noticed that there are actually 2 textboxes appearing. Please refer to the attached image: ...

Tips for keeping a reading item in place while scrolling

To enhance the user experience, I would like to improve readability without affecting the scroll position. Question: Is there a way to fix the scrolling item at a specific position (item with the .active class)? I am looking to maintain a consistent read ...

The react router dom seems to be malfunctioning when attempting to switch between paths

Can anyone help me troubleshoot my React router issue? I'm not seeing any changes when I try to change the path. The code can be found here. .................................... import React from "react"; import Layout from "./Layout"; import Home ...

Rails New Action fails to render HTML during AJAX GET request

Currently, I am in the midst of a project where I made an upgrade to the rails gem from version 2.3.5 to version 2.3.11. However, now I am encountering an issue with getting the controller actions to return HTML via jQuery ajax get requests. An example sce ...

What is preventing me from setting the height of the buttons to be the same as their width?

My website needs a panel on the left side of the screen that contains square buttons, each button representing a different action. However, currently these buttons are stretching horizontally when they should be stretched vertically to match my UI design: ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...

Disable alert bar in PHP/JavaScript after a set amount of time

A question has arisen as I attempt to display an alert box on my webpage. The code in question is: My desire is for this alert box to remain visible for approximately 2 seconds. I have experimented with the following approach: <script> $(".alert- ...

The functionality of ng-show/hide is not functioning properly when applied to dynamically generated HTML elements

Can dynamic HTML content work correctly with ng-show/hide functionality in AngularJS? An alternative solution is to use .show() and .hide() methods to display the desired plots. Scenario: I am adding plots dynamically to a specific HTML element ('sp ...

Information submitted through an ajax request does not get saved in the $_POST array

After successfully executing an AJAX request using GET, I decided to try POST this time. However, when attempting to send data, a baffling error message appeared in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does ...