Set the style properties of one class to match the style properties of another class using JavaScript

I need to dynamically create a div using the Bootstrap panel for displaying it. The div's class will either be "panel panel-success" or "panel panel-danger" based on the server response, which can be either "success" or "failure."

To assign the classes "success" or "failure" to the div, I plan to define in my CSS file that the class "success" is equivalent to "panel panel-success" and the class "failure" is equivalent to "panel panel-danger."

The div in question is one of the cells in a UI-grid and is defined in statusTemplate1, statusTemplate2, and statusTemplate3, as shown below:

JavaScript File

angular.module('Spectacle', ['ui.grid'])
.controller('SpectacleCtrl',
function($scope, $http, $q) {
$scope.loaded = true;
$scope.myData = [];
var statusTemplate1 = '<div class="panel panel-success">{{row.entity.build1.number}} <span class="label label-success">P-{{row.entity.build1.passCount}}</span> <span class="label label-danger">F-{{row.entity.build1.failCount}}</span> <span class="label label-warning">S-{{row.entity.build1.skipCount}}</span></div>';
var statusTemplate2 = '<div class="panel panel-success">{{row.entity.build2.number}} <span class="label label-success">P-{{row.entity.build2.passCount}}</span> <span class="label label-danger">F-{{row.entity.build2.failCount}}</span> <span class="label label-warning">S-{{row.entity.build2.skipCount}}</span></div>';
var statusTemplate3 = '<div class="panel panel-success">{{row.entity.build3.number}} <span class="label label-success">P-{{row.entity.build3.passCount}}</span> <span class="label label-danger">F-{{row.entity.build3.failCount}}</span> <span class="label label-warning">S-{{row.entity.build3.skipCount}}</span></div>';
$scope.gridOptions = { data: 'myData',rowHeight:62 };
$scope.gridOptions.columnDefs = [
                   { field: 'job' },
                   { field: 'build1',cellTemplate: statusTemplate1},
                   { field: 'build2',cellTemplate: statusTemplate2},
                   { field: 'build3',cellTemplate: statusTemplate3},
                   { field: 'build4'},
                   { field: 'build5'}
                 ];

function fnGetList(url)
{
  var deferred = $q.defer();
$http.get(url)
.success(function (data)
{
console.log("Data: " + data.buildList[0].number);
deferred.resolve(data);
});
return deferred.promise;
};

$scope.GetGridData = function ()
{
console.log("In GetGridData: " + "Getting the data");
$http.get('http://localhost:8989/api/job').
    then(function(response) {
        $scope.totalJobs = 2;
        $scope.totalBuilds = 5;
        console.log($scope.totalJobs);
        $scope.jobs = response.data.jobs;
        $scope.loaded = false;
        console.log($scope.jobs);
        console.log('size of the response data:'+ response.data.jobs.length +' ');
        for(var i=0; i<response.data.jobs.length; i++)
        {
          console.log('The jobid for job '+i+' is:'+response.data.jobs[i].id);
          var url = "http://localhost:8989/api/job/"+response.data.jobs[i].id+"";
          fnGetList(url).then(function (content)
          {
              //  Assuming your content.data contains a well-formed JSON
              console.log('Content: '+content.name);
              if (content !== undefined)
              {
                console.log('promise success: '+content);
                console.log('printing grid options:'+$scope.gridOptions.data);
                $scope.myData.push({
                  "job": content.name,
                  "build1": content.buildList[0],
                  "build2": content.buildList[1],
                  "build3": content.buildList[2]
                  // "build4": content.buildList[3].number,
                  // "build5": content.buildList[4].number
                });
              }
          });
        }
    });
};
});

HTML Code

<div class="gridStyle" ui-grid="gridOptions" ng-init="GetGridData()"></div> 

Answer №1

I came up with a solution and here's how I implemented it:

'<div ng-class="\'{{row.entity.build2.status}}\'? \'panel panel-success\' : \'panel panel-danger\'">{{row.entity.build2.number}} <span class="label label-success">P-{{row.entity.build2.passCount}}</span> <span class="label label-danger">F-{{row.entity.build2.failCount}}</span> <span class="label label-warning">S-{{row.entity.build2.skipCount}}</span></div>';

I utilized the conditional statement (condition?true:false) in combination with ng-class

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

How can I include an HTML tag within a select input value in a React.js project?

I am facing an issue while trying to map values from the input field of a select tag. It seems to be returning [Object object] for some reason. When I do not include another tag in the return statement of the map function, the output works fine. However, I ...

Is there a way to make Outlook show only the caption of a link instead of the entire URL?

In my PDF file, I have set up a button for sending an email. The email is a request that needs approval or denial. I want the recipient to respond with just 2 clicks: Click on either "Approve" or "Deny" (a new email will pop up) Click on "send" - and it& ...

The form yields no response and fails to send any data

Ensuring that the form on this site successfully sends the name and phone number is crucial. However, upon clicking the send button, I encounter an empty modal window instead of a response indicating whether the data was sent or not. The contents of the fi ...

What is the best way to refresh my Material-UI checkboxes following updates to certain states in a React JS environment?

One of my latest projects involves an application that visualizes graphs, with all nodes originally colored blue. I included a component in the form of a checkbox that users can interact with to trigger a state change. This change dynamically alters the co ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Assistance needed with sending JSON data to a PHP server using the POST method

I am attempting to transfer JSON data from an HTML form to a PHP server using the POST method. The issue I am encountering is that my code always ends up in the fail block within the callback function. Despite this, the Firebug console (ctrl+shift+J) does ...

The three.js pointLight has been updated from version 67 to version 68

There appears to be a change in the interaction between a pointlight and a plane from version r.67 to r.68. I am currently studying three.js by following along with a book that is a year old. I have simplified the tutorial example to include just a plane, ...

Converting a function to an ES6 class-based style

Hello, I am new to ES6 and eventEmitter. I have created a module in Node.js with an event-based style and now I am trying to convert it to ES6 class style. This is my code: // eventStyle.js const events = require('events'); const util = require ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

What are the steps to switch to a root page after a successful sign-in with Ember-Auth?

After successfully implementing Ember-Auth using a pure token based approach, I am facing a challenge in redirecting users to the root of my app once they sign in. Although I know about actionRedirectable (refer to for details), since I am using a pure t ...

Create a jQuery popup form with a variety of interactive buttons

Is it possible to implement a modal form in jQuery that can be triggered by multiple buttons? All the buttons have identical names and IDs. The goal is to display the modal form whenever any button is clicked. For this example, let's consider having ...

The importance of CSS z-index in optimizing for mobile responsiveness

In my jquery modal dialog box, I wanted to create a shadow effect only between the dialog box and the screen. To achieve this, I added an overlay using a <div>: <div id="overlay" class="overlay btn-hidden"></div> <d ...

What is the best way to perform calculations within a PHP loop for <input> elements and then display the results using a JavaScript loop?

Hello everyone, I'm currently struggling with displaying the calculations from a loop of input tags. What I'm trying to achieve is having 5 rows with input fields. At the end of each row, there should be a span area that displays the calculation ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

Using JavaScript to extract the metadata of an image from a remote location

Is there a way to extract XMP metadata from a JPEG file using JavaScript? I came across a method for doing it in PHP (How can I read XMP data from a JPG with PHP?) which can be adapted for JavaScript using AJAX. However, the issue arises when trying to acc ...

What is the best way to determine the property type dynamically in TypeScript based on the value of another property?

I have been working with Polymorphic relationships and currently have the following TypeScript interface defined: interface SubjectA {} interface SubjectB {} interface SubjectC {} enum SubjectType { SubjectA = 'Subject A', SubjectB = 'S ...

JavaScript: Targeting elements by their tag name within a designated container

When working with PHP, it is possible to use the getElementsByTagName method on any DOM object. However, this concept does not seem to exist in JavaScript. For example, if we have a specific node stored in the variable detailsNode, attempting to use detai ...

Error in Discord.JS: The function message.author.hasPermission is not recognized

As I was working on creating a new command for my discord.js bot to toggle commands on/off, I ran into some issues. Specifically, when I attempted to use the .hasPermission function, I encountered the following error message: TypeError: message.author.ha ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Displaying the division of shares in an HTML table using jQuery to add a new row

I recently worked on transposing a table, adding classes and ids to specific HTML tags, and converting numbers with commas into integers. Now, I am attempting to calculate the percentage share and display it in a new row. Here is the original table for re ...