assess the functionality within an AngularJS expression

Working through a list of dates (jobs.submitted):

<div ng-controller="DashboardController as dashboard">


<div ng-repeat="job in dashboard.jobs | filter: {status: 'started'}" class="row"> 
    <div class="col-xs-3">{{job.submitted}}</div>
</div>

My goal now is to calculate a duration:

(new Date(job.submitted)) - (new Date(job.completed))

When I try to directly input this into the expression, I encounter a syntax error (possibly due to AngularJS not recognizing the Date object).

If I attempt to place it within a function, specifically one in the controller, the evaluation never occurs:

{{dashboard.getDuration(job)}}

It simply shows up as blank.

What would be the most effective approach to handle this situation?

Answer №1

Give this a try

$scope.calculateDays = function(toDate, fromDate, isNegativeAllowed) {
    toDate = new Date(toDate);
    fromDate = new Date(fromDate);
    return Math.round((toDate - fromDate) / (1000 * 60 * 60 * 24));
};

HTML Code

<div ng-repeat="job in dashboard.jobs | filter: {status: 'started'}" class="row">
    <div class="col-xs-3">{{ calculateDays(job.completed, job.submitted) }}</div>
</div>

Answer №2

It's essential to handle this logic in the controller, not directly in the view. Consider implementing it as follows:

Within the view:

{{calculateJobDuration(job)}}

Inside the controller:

$scope.calculateJobDuration = function(job) {
// Convert dates to timestamps
var timestamp1 = new Date(job.submitted).getTime();
var timestamp2 = new Date(job.completed)).getTime();
var duration = timestamp1 - timestamp2;
var formattedDuration = new Date(duration);
return formattedDuration;

}

Answer №3

Check out this method

const start_date = new Date("9/25/2012");
const end_date = new Date("11/30/2013");
const time_difference = Math.abs(end_date.getTime() - start_date.getTime());
const days_difference = Math.ceil(time_difference / (1000 * 3600 * 24)); 
alert(days_difference);

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

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

How can we safely minimize time delay in a date using setTimeout?

I am encountering a significant issue with time delays in the setTimeout function. I have written code for a button to show action at a specific hour, but the problem arises when someone opens the page 30-120 minutes before the action without refreshing, c ...

"Tips on updating the value of a BehaviorSubject with map, filter, find, or findIndex in an Angular

TS arrData = new BehaviorSubject<any>([]); ngOnInit() { const dataArr1 = [ { id: '1', name: 'Room1', spinning: true }, { id: '2', name: 'Room2&apos ...

JS Month Interval Bug Causing Issues with Chart Date

This script retrieves and summarizes download data from MySQL by day, displaying it as a chart. However, there's an issue with the way dates are handled between PHP and JavaScript (Highcharts). While PHP outputs month values from 1 to 12, JavaScript c ...

Rejuvenate your Kendo Chart by utilizing a promise to update the DataSource

I am currently facing a challenge in my Angular application where I need to update the data source for multiple charts and then redraw them. The data source is updated through an Angular service that returns a promise. While I am able to successfully upd ...

Refresh the vuex store values in real-time on the displayed page without the need

I am currently working on displaying variables from my backend that update automatically. To achieve this, I am utilizing Vuex store and nuxt.config.js for transferring the variables. API calls are used to modify the variables in the backend. However, I am ...

Exploring the World of PHP, MySQL, and AJAX

Recently, I came across an issue where I needed to extract values from a MySQL database using JavaScript. What I intended to achieve was to dynamically add a div element when a PHP page is loaded for editing information. The plan was to populate this div w ...

What could be causing a timepiece to be one tick off in vue.js?

I am looking to synchronize the height of one element with another, where the content in the second element changes dynamically. Below is an example code snippet (also available on JSFiddle): var vm = new Vue({ el: "#root", data: { growingTex ...

Tips for swapping text with an image or icon during mobile scaling

As a newcomer to this field, I am facing challenges in finding specific answers. My current objective is to convert text labels into images when the viewport shrinks to mobile sizes. The complexity arises from the fact that I am employing Leaflet, a JavaSc ...

Ways to transfer data from one page to another using AngularJS

Hey everyone, I could really use some assistance with AngularJs. My code is quite lengthy, so I have uploaded a document file for you to review. The code snippet below shows my authentication process for email and password. The customerlogin() method retur ...

arrange a collection within an array containing keys as strings

I am facing an issue with sorting an array of objects. I need to sort the 'list' by 'score' in descending order. var list =[{ '440684023463804938': { score: 6, bonuscount: 2 }, '533932209300832266': { score: 20, b ...

Tips for generating dynamic JSON: Organize the data by filtering it and creating key-value pairs for the appropriate JSON objects

How can I generate dynamic JSON based on input, filter data, and create appropriate key-value pairs for JSON objects? The database schema can be viewed https://i.sstatic.net/iP1JS.png Although I attempted the following code, it did not produce the desi ...

Tips on saving Firebase Storage image url in Firebase database?

How do I store the URL of an image uploaded to Firebase Storage in Firebase Database? When executing the code below, I encounter the following error: Uncaught (in promise) FirebaseError: Function DocumentReference.set() called with invalid data. Unsuppor ...

Issue with updating state following data retrieval in React hooks

Recently, I've been experimenting with an API and working on a React application for data display. However, I encountered an issue while setting the state using the setState method of React Hooks after sending my information through a form request via ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

Exclude child rows from row count in DataTable

I have successfully implemented a feature on my datatable where child rows are toggled when a parent row is clicked. Here is the code I used: $(function() { $('tr.parent') .css("cursor","pointer") .attr("title","Click to expa ...

A guide on integrating MySQL table data into React card elements

After successfully populating a React table within a card (see first code snippet below) with MySQL table data, I am now faced with the challenge of populating a card's information with the same SQL data. The image below displays how cards are curren ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...

Using jQuery to animate based on scrolling to a specific location

Currently, I am working on a smooth scroll effect where an element's top padding reduces gradually as the user scrolls. Simultaneously, I want two child elements to fade - one fading out and the other fading in. While I have achieved the fading effect ...

What is the reason why the 'hide menu onscroll' JavaScript function doesn't perform flawlessly on Safari web browser?

Compatibility with different browsers: works on Firefox, Chrome, and Edge. However, on Safari, the menu (navbar) behaves strangely. It appears when scrolling up but hides (floats up beyond the window) when scrolling to the top of the page without any downw ...