"Keep an eye on the value of elements within Angular framework

I am trying to develop a directive that can be used in the following way:

<div before-today="old">{{exampleDate}}</div>

The purpose of my directive is to check if the date within the div is before "today" and if it is, apply the CSS class "old". However, I am facing an issue because the value of "exampleDate" is fetched through an AJAX call, so it is empty at link time. Do you have any suggestions on how to solve this? Here is what I have come up with so far (but it's not working as expected):

angular.module('myApp').directive('beforeToday', [
  function () {
    return {
        restrict: 'A',
    scope: {

    },
      link: function (scope, element, attr) {
        var date = new Date(element.text());
        var today = new Date();
        if (today >= date) {
          element.addClass(attr.beforeToday);
        }
      } 
    };
  }
]);

Answer №1

If you're looking to implement a similar solution, consider the following:

<div previous-day="old" check-this-date="exampleDate" >{{exampleDate}}</div>

Custom Directive Code

angular.module('myApp').directive('previousDay', [
  function () {
    return {
        restrict: 'A',   
      link: function (scope, element, attr) {


        scope.$watch(attr.checkThisDate,function(newValue,oldValue){
                //validate the new value.
             if (newValue){           
                  var date = new Date(element.text());
                  var today = new Date();
                  if (today >= date) {
                    element.addClass(attr.previousDay);
                  } 
             }
        });
      } 
    };
  }
]);

Answer №2

Instead of creating a custom directive from scratch, consider utilizing Angular's pre-built ngClass.

HTML

<div ng-class="{'beforeToday': detectDate('2013-11-10') }"> text here </div>

Controller:

$scope.detectDate = function(input){
  var date = new Date(input);
  var today = new Date();
  if (today >= date)
     return true;
  else
     return false;
}

ngClass is a useful tool. You provide an object where the key represents the class to add or remove conditionally, and the value is the expression to assess. In this instance, I am using a function as the expression. However, you could also include the expression directly in the HTML. Nevertheless, keeping it within the controller would be more sustainable in the long run.

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 a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Consistent value displayed by addEventListener for each event

Hey everyone, I've been experimenting with different solutions for a few hours now but I'm still stuck on this problem. I have a function that takes JSON as input - I can create an 'a' element: CHECK I can set all the element propertie ...

Is there a more efficient method than repeatedly using _.groupBy?

After performing this action, I end up with an array that organizes the data by month and day of the date, but not by year. This grouping is done to calculate the maximum, minimum, and average values for each available data point. The issue arises from th ...

Tips for shrinking the circumference of a circle

Currently, I have a circular div that has been styled using CSS animations. My goal is to keep the size of the circle consistent when it moves to the bottom, but reduce its size when it bounces back to the top. I am uncertain if this can be achieved solely ...

Running a website on a virtual server

I am working on a webpage that presents results from an angular application, and I want to host it on a web server located on my virtual machine. This will allow my team members to easily access the page daily. However, I am unsure of how to proceed with ...

Is there a way to access the sqlite3 database file in electron during production?

Currently, I have an electron application that I developed using the create-electron-app package. Inside the public folder of my Electron app, both the main process file and the sqlite3 database are located. During development, I can access the database ...

Triggering onClick without interfering with its populated variable

I'd like to add the following code snippet to my document: $('#myDiv).append("<div id='myDiv2' onclick="+extElementConfig.onClickDo+">Do</div>"); The code above uses an object with properties to populate the onClick attrib ...

The XMLHttpRequest only retrieves up to 32 descendant objects from the JSON file, not all of them

I've encountered a peculiar issue with my XMLHttpRequest and JSON file. While I can successfully access the data, it seems to only iterate through 32 child objects within each parent object. Take, for example, this snippet from the routes.json file: ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

What could be causing my MVC Action to not recognize the AJAX object that was passed to it

Despite a successful Ajax call, the passed object appears empty. This involves passing a cart object to a controller action in a straightforward setup. The call goes through, but the object is empty upon reaching the Action. The payload being sent (in C ...

AngularJS - Implementing a sliding down menu feature with the ng-click directive

Is there a way to modify my menu button so that it slides down and up when clicked, instead of just showing and hiding? HTML: <div class="nav"> <nav class="primary-nav" ng-show="showMenu" ng-class="{true: 'showMenu'}[showMenu]"> ...

Tips for concealing a div upon reaching a specific scroll point, even with varying content sizes

Hey there! I am completely new to web programming and currently working on a landing page. The challenge I'm facing is that the content in the first column is dynamic, meaning it can vary in length. I'm looking for a way to hide my call-to-actio ...

The promise is returning an undefined value when attempting to access the array within

I'm currently delving into NodeJS to create some automation scripts, but I've hit a roadblock that's stumping me. By utilizing the Google Spreadsheet API and the "promisify-node" package, I'm trying to fetch data from a spreadsheet and ...

Is there a way to confirm that a file has been successfully downloaded through JavaScript?

Looking for a way to confirm if a file has been successfully downloaded using JavaScript. Our project utilizes frameworks such as Selenium, Cucumber, and Nightwatch. I have come across some solutions in C, but they do not seem to be suitable for my projec ...

The list in Jquery UI Autocomplete is not updating correctly

Currently, I am using jQuery UI Autocomplete in conjunction with WebSockets to fetch and display a list of options. Each time a keystroke is detected on the input field (.keyup()), a call is made to retrieve the list. However, I have encountered an issue w ...

The Cordova Network Information Plugin is experiencing some functionality issues

I successfully developed a Mobile application using Cordova, Onsen UI, and Vue.js. While addressing network connectivity issues, I incorporated the cordova plugin cordova plugin add cordova-plugin-network-information For determining the type of connectio ...

Utilizing JavaScript to Load and Showcase Images from a Temporary Image to imgsrc

How can I dynamically display images from the temporary image array 'tempimages' onto the 'img' element with the 'src' property? I have written a code that attempts to display temporary images from 'tempimages[]' on ...

Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element ...

The functionality of JQuery .change() is limited to one occurrence

Here is my JavaScript code snippet: jQuery(document).ready(function(){ const select = $('...'); //select element const input = $('...'); //input element select.change(doSomething()); input.change(doSomething()); f ...

Looking for assistance with increasing the output size in JavaScript

As a beginner in JavaScript, I managed to create a form with a textarea and a button to display the text from the textarea in a div tag. Additionally, I added two buttons that are meant to increase the size of the text in the div tag when clicked, as wel ...