Using Angular.js to Implement Filtering with Intervals

I have implemented a unique custom angular.js filter for formatting datetime objects:

function relativeTimeFilter()
{
    return function (dateObj) {
        return getRelativeDateTimeString(dateObj);
    };
}

function getRelativeDateTimeString(dt)
{
    if(!dt) return "undefined ago";

    var delta = dt.getSeconds();
    if (delta < 0) return "not yet";
    if (delta < 1 * 60) return delta == 1 ? "one second ago" : delta + " seconds ago";
    if (delta < 2 * 60) return "a minute ago";
    if (delta < 45 * 60) return Math.floor(delta/60) + " minutes ago";
    if (delta < 90 * 60) return "an hour ago";
    if (delta < 24 * (60*60)) return Math.floor(delta/60/60) + " hours ago";
    if (delta < 48 * (60*60)) return "yesterday";
    if (delta < 30 * (24 * (60*60))) return Math.floor(delta/60/60/24) + " days ago";
    if (delta < 12 * (30 * (24 * (60*60))))
    {
        var months = Math.floor(delta/60/60/24/30);
        return (months <= 1) ? "one month ago" : (months + " months ago");
    }
    else
    {
        var years = Math.floor(delta/60/60/24/365);
        return (years <= 1) ? "one year ago" : (years + " years ago");
    }
}

module.filter("relativetime", relativeTimeFilter);

While using this filter, I want the relative time to be continuously updated. For example, one second ago should update to 2 seconds ago after one second passes.

Initially, I tried applying setInterval in my controller function to trigger the filter at regular intervals:

setInterval(function() {$scope.$apply()}, 1000) // placed in controller function

However, this approach did not work as expected. Do you have any suggestions on how to achieve this periodic update with the filter?

Answer №1

It seems unlikely that a filter will solve this issue. The problem with $scope.$apply() not working is due to it only detecting actual changes in the data. Therefore, the filter does not get triggered.

Instead, you should modify the data being accessed in your controller. Opt for $timeout over setInterval as it aligns better with the digestion lifecycle.

You might want to consider implementing a directive for this purpose.

app.directive('relativeTime', function($timeout) {

  function update(scope, element) {
    element.text(getRelativeDateTimeString(scope.actualTime));
    $timeout(function() { update(scope, element); }, 1000);
  }

  return {
    scope: {
      actualTime: '=relativeTime'
    },
    link: function(scope, element) {
      update(scope, element);
    }
  };
});

To use the directive, follow this format:

<div relative-time="theDate"></div>

In addition, I noticed an issue in your getRelativeDateTimeString function. Make sure to base the time difference calculation on the current time. Using getSeconds only provides the seconds of the specified time:

var delta = parseInt(((new Date().getTime()) - dt.getTime()) / 1000);

For reference, here's a functional CodePen example.

Answer №2

If you need a working example of using the directive to update the time, check out this jsfiddle link below.

http://jsfiddle.net/vishalvasani/xRg3j/

This particular demo utilizes:

$timeout

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

What is the easiest way to transform this json data into plain text format?

Snippet: if (message.content.startsWith(config.prefix + 'shop')) { const shop = LabyMod.getShop('all').then(shop => shop.map((sh) => sh.name)); const awaitShop = await shop console.log(JSON.stringify(awaitShop)) ...

The display of temporary headers - Nodemailer - AJAX

I keep receiving a warning in the request header that says: Provisional headers are shown. I'm struggling to identify the root cause of this issue. This warning prevents the readyState from changing and my callbacks on the eventhandler onreadystatecha ...

React's componentWillMount() does not support the use of "if" statements

I've been working on a component called "App" that includes a function componentWillMount. The purpose of this function is to redirect React Router when a certain condition is false. componentWillMount() { const isLoggedIn = session.getLogin() ...

Merge various JavaScript files together into a single consolidated JS file

I've been working on my web application with jQuery and am looking to incorporate multiple additional jQuery script files into one page. After doing some research, I found that Google recommends consolidating all of the jQuery script files into a sin ...

Steps for implementing a JavaScript script to modify all values within a table

I am facing an issue where I need certain "td" elements to disappear when the date associated with them has passed. However, currently only the first column is affected while others remain untouched. <script type="text/javascript"> //<![CDAT ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

What is the most effective way to loop through a JSON object and apply filtering based on user input?

I am currently working with a dataset stored in a MongoDB database, and below is the format of the data. I have been looking for something similar to streams functionality in Java but haven't had any luck. Data from the Database: [ { &quo ...

Utilizing numerous controllers within a single page

I recently decided to organize my angularJS controllers into separate files for better readability. However, I encountered an issue where the controller defined in a separate file is not functioning at all. Could this problem be related to having my MakeGr ...

Synchronizing the DOM with the Database in a React Component/View: A Step-by-Step

I recently developed a list component in React, but I'm facing two significant challenges. Although the item gets removed from the database, the change is only visible after refreshing the page. You might have noticed that the list number or ID colu ...

Guide to effectively utilizing jQuery Deferred within a loop

I have been working on a function that needs to loop through a dataset, updating values as it goes along using data from an asynchronous function. It is crucial for me to know when this function finishes running the loop and completes all updates. Here is ...

Interactive canvas feature in a browser window with scrolling capabilities (drag and drop functionality)

One challenge I'm facing is when drawing in a canvas on a browser window that has a vertical scrollbar. The figures are in the correct position, and it's possible to interact with them by grabbing and making connections. However, this interactio ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Introducing a delay in an observable causes incomplete data to be received in Angular using rxjs

Currently, I am facing an issue in my code where I am trying to introduce a delay using timer(500). However, the problem is that it is only returning partial data. Instead of the expected 17 fields, it is only returning 2 fields. Below is my code snippet f ...

Testing Angular: Inability to achieve full code coverage for Ternary branch in unit testing

Currently, I am attempting to test a ternary branch that utilizes the window.location property. @Injectable() export class ABCService { private hostUrl = (window.location.host.indexOf('localhost') > -1) ? 'example.com' : window.lo ...

Sending a post request from JavaScript to Django Rest Framework

I am working with a DFR api endpoint: url = http://example.com/api/data/ The URL of the page where I am running JavaScript code is: http://example.com/page/1/ I have logged in as User1 in my browser. POST request - from DRF browser API - successful. G ...

Obtaining cookies from a separate domain using PHP and JavaScript

Imagine you have a cookie set on first.com, called "user". Now, the goal is to retrieve that cookie on second.com using JavaScript and AJAX. Unfortunately, it's not working as expected and you're receiving xmlHttp.status=0. Here is a sample code ...

Version 1.0 and higher of Ionic do not display the side menu when using tabs

I have developed an app using Ionic that includes a side menu with tabs feature. The side menu displays correctly when using Ionic version 0.9.27, but it does not show up when the version is 1.0 or higher. What could be causing this issue? HTML Layout & ...

Three.js: Loading DAE Files

Having trouble loading a DAE file in Three.js. Can anyone offer some assistance? I have the model.dae file in the same directory as my index.html, but when I load the page, it's just showing a black screen. I originally had an FBX file and exported ...

The addition of ngRoute causes the controller in AngularJS to malfunction

Currently, I am attempting to implement routes in my angularJS application and have encountered an issue where integrating 'ngRoute' into the app causes the main controller to malfunction. Furthermore, I am experiencing difficulties with ngRoute ...

Maintaining the generic types in mapped types in TypeScript

In my current project, I have a unique design where a class contains instance methods that act as handlers, each representing a specific operation. These handlers take a reference as input and assign the output to a second parameter. To simplify this proce ...