Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa.

<form name="myform" data-ng-submit="submit()" data-ng-controller="Ctrl" id="submitForm">
        <p data-ng-repeat="beat in beats">
            Station ID: {{ beat.stationID }}
            Uptime: {{ beat.lastPingedAsString | date : 'mediumTime'}}
        </p>
        <input type="submit" id="submit" value="Submit" />
    </form>

I have been researching how to apply formatting using classes, but I haven't been able to get it working properly.

EDIT: Just to clarify, my goal is to create a function that checks if 5 minutes have passed and then changes the color from green to red. Apologies for any confusion.

EDIT2: Here is the original sample (unformatted). I will now implement the new code.

Station ID: default Uptime: Jul 18 2014 2:09PM

Answer №1

Here is a function added to the controller scope:

$scope.calculateTimeDifference = function(pingDate) {
  var now = new Date();
  var differenceInMs = (now - pingDate);
  return Math.round(((differenceInMs % 86400000) % 3600000) / 60000);
}

<form name="myform" data-ng-submit="submit()" data-ng-controller="Ctrl" id="submitForm">
    <p data-ng-repeat="beat in beats" ng-class="{longtime: calculateTimeDifference(beat.lastPinged) >= 5}">
        Station ID: {{ beat.stationID }}
        Uptime: {{ beat.lastPingedAsString | date : 'mediumTime'}}
    </p>
    <input type="submit" id="submit" value="Submit" />
</form>

css: .longtime {color: red}

This implementation assumes that there is a beat.lastPinged stored as a JavaScript date. Alternatively, you can encapsulate the business logic within calculateTimeDifference and simply return true or false.

ng-class assigns a specified class if the condition on the right evaluates to true.

Another directive to consider is ng-style, which applies similar functionality for CSS style attributes.

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

managing arrays in JavaScript with multiple tables

**I have successfully written code for calculating the sum of inputs in one table** $('#example122').on('input', '.calculate', function () { calculateTotal(); }); function calculateTotal() { var grandTotal = 0; $ ...

invoke scrollToPosition function in React Native

I am trying to execute a function once the scrolling momentum is finished in my react native SectionList. After going through the documentation, I discovered onMomentumScrollEnd. However, the problem is that onMomentumScrollEnd only works when we manually ...

Setting up Angular is a crucial step in starting your development journey

I'm currently in the process of developing a web application using Angular and have successfully written some HTML code. However, I'm encountering an issue where the Angular functionality seems to be missing. When I insert a test angular expressi ...

Displaying MongoIds in HTML output for the user

Currently, I am in the process of developing a web application that utilizes MongoDB as its database management system. One challenge I am facing is finding a way to accurately identify which object the user has selected from a list on the screen, and the ...

What is the best way to parse a JSON stream from a secure https source using perl

I will provide detailed information on the task at hand. My objective is to establish a connection with an https URL that streams JSON data, look for specific keywords using REGEX as the data flows in, extract the matching JSON element, decode it, and the ...

Header with a dropdown select option

In the process of developing a monitoring system, I am in need of a feature that allows users to select varying numbers of days. Here is the desired style: Previous [Dropdown Selection] Days https://i.sstatic.net/ysk6X.png Ideally, I do not want any bor ...

Accessing images from subreddit using reddit API

Seeking inspiration from reddit API, I am interested in extracting images from a specific subreddit (http://www.reddit.com/r/VillagePorn) and showcasing them on a webpage. I have observed similar functionality on other websites (specifically, imgur.com/r/* ...

The error message "TypeError: Router.use() expects a middleware function, but received a [type of function]" is a common occurrence in FeathersJS

Struggling to bind a method to my /userAuthenticationInfo route, I've made several adjustments in my code based on other posts related to this issue but still unable to make it work. I am using feathersJS's express implementation, and even with e ...

Error loading GLTF file

I'm having trouble displaying a GLTF model using three.js. If someone could help me identify the issue in my code, I would greatly appreciate it. import {GLTFLoader} from "./GLTFLoader.js"; var scene = new THREE.Scene(); ...

React: Updating State with the Spread Operator and Array Method to Add Elements to an Array

Link to my jsfiddle code snippet: https://jsfiddle.net/ilikeflex/r2uws1ez/30/ I've been attempting to update the state in React by accessing the previous state. There are three different cases where I'm trying to achieve this, but I'm havin ...

What is the best way to set up a server in React using Express or HTTP?

I am currently in the process of developing a web application using react js. In order to create a server for my client within the project, I have decided to utilize either express or http. Here is the code snippet that I attempted: import React from " ...

"Headers cannot be set once they have been sent to the client... Error handling for unhandled promise rejection

Having trouble with cookies in the header - specifically, encountering an error at line number 30. The error message reads: "Cannot set headers after they are sent to the client." Additionally, there is an UnhandledPromiseRejectionWarning related to a prom ...

Phonegap app failing to run Ajax request properly

I have recently updated my Android app using phonegap build to the latest version, cli-5.2.0. Here is a snippet of my config: <preference name="phonegap-version" value="cli-5.2.0" /> Additionally, here is how my overall configuration looks like: & ...

Having an issue with TypeScript and React where the onChange event on the <select> element is only setting the previous value instead of the current value when using the useState hook

I'm currently developing a scheduling web tool. One of the key features I'm working on involves calculating the total hours between two selected times, startTime and endTime. These times are chosen via a form and stored using the useState hook: ...

Click event doesn't trigger the 'else if' statement in jQuery

Having trouble with a button click issue. In the following code, when the button is clicked, it checks if the text on the button is "day". If so, it changes the background-color of the body to red and updates the button text to "night". I am struggling wit ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

Using AJAX and Rails to set session variables in the presence of appcache

When making an ajax call to "updateUser," the following code is executed: puts session[:user_id] user = User.find(params[:user_id]) if user session[:user_id] = user.id session[:user_name] = user.first_name + " " + user.last_name puts session[:user_i ...

Extension for Chrome

My goal is to develop a Chrome extension that, when a specific button in the extension is clicked, will highlight the current tab. However, I'm encountering some challenges. Currently, I have document.getElementById("button").addEventListen ...

Is there a way to configure Cordova to utilize Yarn JS instead of NPM when installing plugins?

Updated Question: When adding plugins to my Cordova project, I currently use the command cordova plugin add x, which I believe utilizes npm in the background. Is there a way to switch out npm for Yarn within Cordova? This change would greatly impact cach ...

The error message indicates that the Worklight adapter is an object, not a function

Upon deploying the Worklight adapter to the production server, I encountered an error when the adapter called a Java code from JavaScript: Procedure invocation error. Ecma Error: TypeError: Cannot call property updateProposal in object [JavaPackage com.id ...