Is there a way to refresh the countdown timer?

I am working on creating a countdown timer using directives and want to add some CSS styles like fade-out when the time is changing. My issue lies in the HTML binding where the time is not updating visually, although it does change in the console.

Here's my HTML:

<body ng-app="myApp" ng-controller="myCtrl">
<count-down-timer count-down-time=5000></count-down-timer>
 {{userCountDownTime}}
</body>

And here is my JS code:

app.directive('countDownTimer', function () {
return {
restrict: 'E',
replace: true,
link: function (scope, elem, attr) {
  scope.userCountDownTime = attr.countDownTime;
  initiate();
  function initiate() {
    console.log("initiated")
    var myVar = setInterval(decrement, 1000);
  };

  function decrement() {
    console.log("decrement");
    scope.userCountDownTime--;
    console.log(scope.userCountDownTime);
    return;
  }
}
 }});

Answer №1

Check out the plunkr example:

https://plnkr.co/edit/FSOtUYcoPhLEwp5paNin?p=preview

.directive('countDownTimer', function ($interval) {
return {
restrict: 'E',
replace: true,
link: function (scope, elem, attr) {
  scope.userCountDownTime = attr.countDownTime;
  initiate();
  function initiate() {
    console.log("Starting countdown")
    var myVar = $interval(decrement, 1000);
  };

Make sure to include the $interval service, which acts as a wrapper for window.setInterval https://docs.angularjs.org/api/ng/service/$interval

Answer №2

To inform angularJS about a change, you must trigger $scope.$apply. This can be done securely using $interval.

app.directive('countDownTimer', function ($interval) {
    return {
        restrict: 'E',
        replace: true,
        link: function (scope, elem, attr) {
            scope.userCountDownTime = attr.countDownTime;

            $interval(decrement, 1000);

            function decrement() {
                scope.userCountDownTime--;
            }
        }
}});

UPDATE: Altered to utilize $interval rather than $timeout.

Answer №3

Consider modifying your instruction as follows:

app.directive('timerCountDown', [ '$interval', function ( $interval ) {
return {
restrict: 'E',
replace: true,
link: function (scope, element, attributes) {
  scope.remainingTime = attributes.countDownTime;
  startCountdown();
  
  function startCountdown() {
    console.log("Countdown started");
    var countdownInterval = $interval(decrementCounter, 1000);
  };

  function decrementCounter() {
    console.log("Decrementing counter");
    scope.remainingTime--;
    console.log(scope.remainingTime);
    return;
  }
}
 }}]);

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

JS and its dynamic color changes

A game has been developed using JavaScript and HTML. The game features a table with cells that are assigned IDs for toggling colors using an onClick function. The objective is simple: when a cell is clicked, all neighboring cells, including the clicked one ...

Achieving a child div to occupy the entire available space when the parent is specified as `mx-auto` can be accomplished using Vue and Tailwind CSS

Sorry if this seems like a basic question, I'm still getting the hang of Vue and tailwind. In my parent template, it looks like this: <template> <div class="mx-auto mt-4 max-w-3xl"> <slot></slot> </div> ...

The background of an HTML button does not appear in IE8

My buttons are not showing up in IE8. I tried adding background: transparent url('..'), but it didn't help. Here is the code: .wpcf7 input.wpcf7-submit { background: url("/wp-content/themes/ASC/images/<?=ICL_LANGUAGE_CODE;?>_submi ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

Displaying incorrect symbols with icon fonts

I have successfully integrated icon fonts into my simple web page. Check it out on jsFiddle here My design is similar to this example, but instead of bars, I see a snake icon displayed. How can I fix this issue with the fonts? Here is the code snippet: ...

Ajax received a response from http 409 and is now parsing it

Hey there! I've been working on parsing out the message object using Ajax, and I'm having a bit of trouble getting a reference to messages.msg. It's strange because it displays perfectly fine in Postman, but for some reason, I can't see ...

Drawing the canvas is taking place prior to the image being fully loaded in JavaScript

Currently, I am in the process of creating a collage using images that are all sized at 174x174 pixels. The images are stored on my server, and while my program can locate them successfully, it requires me to click the "save image" button twice for them to ...

Transferring Information Across Javascript Documents

I am facing a dilemma with using JSON data generated by one script in another script. I am unsure where to begin and have considered saving the JSON string to a text file for the second script to use, but this feels like a workaround rather than a proper s ...

Best Practices for Closing MySQL Connections in Node.js

Currently, I am working on a project using Node.js in combination with Express and MySQL. My main concern at the moment is regarding the closing of the connection to MySQL. The code snippet for this operation is provided below: iniciarSesion(correo_el ...

How can I apply a specific style class to a table row when I already know the table's id?

Hi there! I'm new to jquery and trying to enhance the functionality of my application which has multiple HTML tables in JSP's. My goal is to use jQuery to dynamically apply a CSS style class when hovering over a row. Currently, I have the followi ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

I am interested in creating a ranking system in JavaScript using JSON data based on points

I have a desire to create the following: var users = {jhon: {name: 'jhon', points: 30}, markus:{name: 'Markus', points: 20}}; // I want it to return like this 1. Jhon with number of points: 30 // 2. Markus with number of points: 20 ...

What causes the variance in AJAX errors between IE and Chrome browsers?

Consider the code example provided below: <script> function xyz() { $.ajax({ type: "GET", url: "https://zx/xyz/uvw", timeout: 6000, dataType: "jsonp", ...

Styling tricks for rotating carousel images using CSS animations

I'm currently working on a carousel component that functions without the use of JavaScript. While I have made significant progress towards my goal, I am facing challenges with the animation itself. The desired behavior is for the slides to animate o ...

Combining selected boxes through merging

Looking to create a simple webpage with the following requirements: There should be 10 rows and 3 boxes in each row. If I select 2 or more boxes or drag a box, they should merge together. For example, if my initial screen looks like this: and then I se ...

Display or conceal a text field in Vue 2/Vuetify 1.5 depending on whether a checkbox is selected, with the possibility of duplicated

I've created a product checkbox selection feature that dynamically shows or hides text fields based on the user's selection. Unfortunately, there is a glitch in the system where selecting the second item causes duplication of text fields from th ...

When scrolling, all sections display above the stationary header

On my home page, I have a header that remains fixed at the top of all sections. However, when I scroll down, the contents and sections appear above the fixed header, making it look like a background. Is there a way to ensure that all images and content go ...

What is the recommended lifecycle hook in Vue.js2 to execute a function when the page is loaded?

I have a dynamic table that can be filled with various numbers of rows, and I want to add an overlay before the data is loaded using my applyOverlay() function. Below is the structure of my HTML: <table id="table" class="datatable" s ...

I'm having an issue with a jQuery navigation plugin that is causing the entire page to refresh. Does anyone

My website includes a jquery slider plugin that I use for navigating between slides. I decided to apply absolute positioning for the previous/next slide navigation, but now I am facing an issue where the navigation refreshes the entire page. Can someone ...

Is there an obstacle hindering the load event?

There's something strange happening on a website I created. The page content loads in 5 or 6 seconds, but the DOMContentLoaded and Load Event don't actually fire until 1 minute and 10 seconds later. When I reload the page during loading, it load ...