AngularJS Timer is not correctly syncing with DOM value

As a backend developer, I've been working tirelessly to create a timer by comparing two different date formats. While the initial part of the script works perfectly, I face challenges when trying to make a recursive call as nothing seems to bind.

I've experimented with various approaches such as passing it into a function, utilizing $interval, setInterval, and more. The core issue lies in my inability to extract the loop value and bind it to my DOM.

Below is a snippet of my code where I set all variables for the countDown() function:

$scope.timer.list = {};
$scope.timer.date = new Date();
$scope.timer.list.D = '00';
$scope.timer.list.M = '00';
$scope.timer.list.Y = '00';
$scope.timer.list.h = '00';
$scope.timer.list.m = '00';
$scope.timer.list.s = '00';
$scope.begin = {};
$scope.begin.date = {};
$scope.begin.timer = {};
$scope.counter = {
    show: false,
    text: '00:00'
};
setInterval(function() {
    $scope.obj = {
        show: $scope.countDown($scope.privateshowcase.begin_at).show,
        text: $scope.countDown($scope.privateshowcase.begin_at).text
    }
    $scope.counter = $scope.obj;
}, 1000);

In addition, here is the function definition:

$scope.countDown = function(begin) {
    // Function logic here...
}

'begin' format: 'YYYY/MM/DAY HH:MM:SS'

Despite facing some hurdles, I have managed to develop a very functional timer that converts numbers from 1 to 9 into 01 to 09, transforms 60 into 00, and can effectively compare two distinct times.

Answer №1

It seems like things are being made more complicated than necessary. I've developed a straightforward countDown component using angularjs 1.6.0 (which can also be adapted for older angularjs versions) to compare an input Date with the current now Date.

You have the flexibility to adjust the input and modify dates to witness changes in the component, as long as you maintain the correct date format.

Note on dates: A simple method to compare dates is shown below:

var date0 = new Date("2017-09-12T14:45:00.640Z");
var date1 = new Date("2017-09-13T14:45:00.640Z");

var dateDiff = new Date(date1.getTime() - date0.getTime());
// "1970-01-02T00:00:00.000Z"

Even though dateDiff appears odd, it essentially represents one day from the starting date of 1970-01-01T00:00:00.000Z.

Incorporating this, leverage angularjs to perform its magic.

{{ dateDiff | date:"d \'days\' hh:mm:ss" }}

Furthermore, if dealing with dates in JavaScript's typical form doesn't suit your preferences, consider utilizing angularjs-moment, which offers date and time functionality from momentjs without encountering the drawbacks of JavaScript dates.

The operational code is displayed below:

angular
  .module('app', [])
  .run(function($rootScope) {
    $rootScope.countDownToDate = new Date().addDays(2);
  })
  .component('countDown', {
    template: '{{ $ctrl.timer | date:"d \'days\' hh:mm:ss" }}',
    bindings: {
      to: '<'
    },
    controller: function CountDownCtrl($interval) {
      var $this = this;

      this.$onInit = function() {
        $interval($this.setTime, 1000);
      };

      $this.setTime = function() {
        $this.timer = new Date(new Date($this.to).getTime() - new Date().getTime());
      }
    }
  });

// bootstrap the app
angular.element(function() {
  angular.bootstrap(document, ['app']);
});

// extension to add days on date
Date.prototype.addDays = function(days) {
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + days);
  return dat;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<div>
  <center>
    <h1>
      <count-down to="countDownToDate" />
    </h1>
    <label for="countDownToDate">To Date</label>
    <input type="datetime" name="countDownToDate" ng-model="countDownToDate">
  </center>
</div>

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

Adding an additional parameter in the ListItem onMouseOver function

Within my React code base, I have a material-ui ListItem that looks like this: <ListItem button key={currIndex} onMouseOver={handleOnMouseClickOnListItem}> The handler function in my code (using Flow typing) is as follows: const handleOnMouseClic ...

A comparison between Buffer.byteLength and file size

I'm facing an issue with file size discrepancies. I have a file that is reported as 51Mb in Finder, but when uploaded to the server, the byteLength of the Buffer shows a much smaller size. Could this difference be due to the file type or other propert ...

Stop event bubbling in Vue.js for router link

I'm working with the following HTML template... <template> <li class="nav-item" style="z-index:9"> <router-link :to="link.path" @click.native="linkClick" ...

Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express ...

The custom layout in NestJS version 13 failed to display

I have implemented NextJs 13 in my project for building purposes. I am trying to use CustomLayout as the primary layout for my entire website. Even though there are no errors, I am facing an issue where the CustomLayout does not display as expected. ...

React material ui is not compatible with custom styles that are applied to components

I've developed a unique UserIcon Component that showcases an icon along with accompanying text. Take a look at the code snippet below: import React from "react"; import PropTypes from "prop-types"; import { withStyles, Avatar, Typography } from "@mat ...

Ways to incorporate vector .svg images into a D3js tree diagram

var treeData = [ { "name": "Top Level", "parent": "null", "remark":"yes", "children": [ { "name": "Level 2: A", "parent": "Top Level", "remark":"yes", "children": [ { "name": "So ...

CSS grid challenges on a massive scale

My CSS grid timeline is currently generating around 1300 divs, causing performance issues. Is there a way to style or interact with the empty nodes without rendering all of them? I also want each cell to be clickable and change color on hover. Any suggest ...

I encounter issues when entering conditions in my JavaScript code

Being new to JavaScript, I'm trying to save the Vector position and use two buttons (forward and backward) to move the Camera to that specific location. I also attempted to incorporate 'gsap' for smooth movements, but unfortunately, the code ...

Increase the size of the text box as more text is entered (similar to how it works

I am looking to replicate the comment feature from Facebook exactly. For instance, if I input a sentence that goes beyond the width of the textbox or hit enter for a new line, the textbox should drop down by one line to fit the new content. Visual Represe ...

Can you fill two dropdown menus with an array of choices?

I'm encountering an issue with using an array to populate two different select boxes. The first select box gets populated correctly, but when trying to add the same list to the second select box, it clears the first one and automatically selects the l ...

How can I set a default radio button selection when the page is loaded?

Input your radio button code below: <ion-radio ng-model="data.gender" ng-required="true" ng-value="'male'">Male</ion-radio> <ion-radio ng-model="data.gender" ng-required="true" ng-value="'female'">Female</ion-rad ...

Is there a way in CSS/3 to dynamically adjust the height based on the width?

Is there a way in CSS/3 to maintain the shape ratio of a div while keeping it responsive? Let's say the container is 100px wide. For example: width: 100%; height: 100%-of-width; Result: The div is 100px wide and 100px high. Another example: ...

What are some strategies to optimize debugging and troubleshoot errors in a Node.js http post request?

This particular example may seem a bit lacking in context, I admit. Nonetheless, when attempting this request, the following error surfaces: TypeError: Invalid data, chunk must be a string or buffer, not object My suspicion is that the issue lies within ...

"Deploying code to Heroku using Node.js: A guide to adding git commits directly on

Currently, as I delve into learning Node and Git, I'm faced with a dilemma involving my Heroku app. The app is designed to interact with a local file on the server that serves as a basic JSON database. The issue arises when I attempt to manage this f ...

Steps for building JSX with a loop

Recently diving into the world of React and Javascript, I've been attempting to assemble a JSX 'tree' dynamically using a loop rather than hard-coding the data. However, I find myself facing a hurdle where Visual Studio Code insists on havi ...

Accordion - Conceal Previously Revealed Items

I'm currently working on finding a solution to hide all child sections that are open in my accordion when a new header is clicked. I've included a jsfiddle link to show what I have so far. Any suggestions on how to close the opened sections would ...

Setting the font size for the entire body of a webpage globally is ineffective

Technology Stack: Nuxt.js + Vuetify.js Problem: Unable to set global body font size Solution Attempt: I tried to adjust the body font size to 40px in ~/assets/style/app.styl: // Import Vuetify styling ...

A quick guide on updating table values in Laravel framework without the use of forms or JavaScript

Currently, I am immersed in my project where I need to fetch data from a table named 'Clients' in a database and exhibit it. Initially, this was quite straightforward. However, I now wish to modify certain information in the table. The challenge ...

Blocking Data Events in Node.js

I recently started experimenting with Node.js and I'm grappling with the concept of non-blocking functions. I have created a server in Node.js that needs to handle multiple clients in C# through TCP connections. I want to ensure that a client does no ...