What is the best way to utilize $watch in a directive to dynamically update a class without using jQuery?

I'm currently in the process of developing an application that requires polling live data every 10 seconds. When there is a change in the data, it needs to be highlighted within the view. I have achieved this using jQuery, but now I would like to implement it with an Angular template instead.

Here is my controller:

angular.module('myApp.controllers', [])
.controller('MainCtrl', ['$rootScope', 'liveDataPoller', function($rootScope, liveDataPoller) {
    $rootScope.liveData = liveDataPoller.getData();
}]);

This is my directive:

angular.module('myApp.directives', []).
directive('liveValue', function() {
    return {
        restrict: 'A',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if(newValue && oldValue && (newValue !== oldValue)) {
                    if(newValue < oldValue) {
                        element.removeClass("up").addClass("down");
                    } else {
                        element.removeClass("down").addClass("up");
                    }
                } else {
                    element.removeClass("down").removeClass("up');
                }
            });
        }
    }
});

This is my view:

<div live-value val="liveData.randomInteger">{{liveData.randomInteger}}</div>

Is it possible to update the add/remove class functionality to utilize transclude and a template instead? I prefer not to mix jQuery into this implementation.

If anything is unclear, please don't hesitate to ask for clarification.

Answer №1

Check out this demo: http://plnkr.co/edit/uXhOceXYWLLkmRkzxx1h?p=preview

By utilizing a scope variable, you can easily monitor changes and implement two-way binding to dynamically update the class attribute in the HTML.

app.directive('liveValue', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      data: '=', change:'='
    },
    template: '<div class="{{change}}">The value({{data}}) has changed to: {{change}}</div>',
    link: function(scope, element, attrs) {
      scope.change = '';
      scope.$watch('data', function (newValue, oldValue) {
        if (newValue == oldValue) {
          scope.change='nochange';
        } else if(newValue<oldValue){
          scope.change='down';
        } else {
          scope.change='up';
        }
      });
    }
  }
});

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 could be the reason for my directive's selection not getting bound to the controller?

I'm currently working on a straightforward directive that acts as a wrapper for a dropdown. My goal is to have an attribute called "selectedOption" (or selected-option) that can be two-way bound to the controller. I've declared this property in t ...

Ways to remove newly added tasks using JavaScript function?

I have an existing list of li elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for loo ...

What could be causing the Ioncol not triggering the Onclick event?

I am facing an issue where my onclick event is not working on an ion-col. The error message says that the method I call "is not defined at html element.onclick". Here is a snippet of my code: <ion-row style="width:100%; height:6%; border: 1px solid # ...

Tips on transmitting form information from client-side JavaScript to server-side JavaScript with Node.js

Having created an HTML page with a form, my goal is to capture user input and store it in a JSON file. However, I've run into some confusion... In the process, I utilized the express module to set up a server. My mind is juggling concepts such as AJA ...

Issues with invoking JavaScript functions

In my HTML page, I'm calling a function from a separate .js file named jQuery.loadjson.js. The syntax being used is $('#data').loadJSON(data); #data refers to a div element, and data is a JSON object. However, when I try to debug this in Fi ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

Retrieve the data attribute from a select box that was created dynamically

Following an AJAX request, I have successfully generated two select boxes: $("#job_id").change(function() { var id = $(this).val(); $.ajax({ url: '', type: 'POST', dataType: 'json', dat ...

Leveraging Vue.js to preload data with client-side rendering

When it comes to server-side rendering in Vue, like with Nuxt, the process involves grabbing data using the serverPrefetch() function and rendering content on the server side. This allows for the request to return data to the user only after the initial do ...

Having problems with the MongoDB save() function when it comes to an array of objects

This piece of code is designed to handle post requests for sending messages between users. It works well when the message is not part of an existing message string (i.e., typeof existingMessageIndex === 'undefined'). The error ("error saving outg ...

Steps to deactivate a textarea in angularjs based on a selected option's value meeting a specific condition

Hello, I am a newcomer to AngularJS and I am looking to disable the textarea when a specific option is selected from a dropdown menu. I attempted to use ng-disabled="(here my ng-model value)" but unfortunately, it did not work as expected. If creating a ...

Tips for grouping radio buttons that span multiple rows within an ag-grid

I am currently working on a grid layout that consists of multiple rows, with each row containing a radio button as illustrated in the snapshot below: https://i.sstatic.net/O8i0r.png Here is the code snippet for the column definition of the radio button: ...

What is the method to deactivate all events in React components using refs?

Currently, I am utilizing TreeView from Material-ui along with a text field for searching other items on the screen. Although TreeView and TextField are unrelated components. However, I have encountered an issue where if I click on a TreeView node and the ...

Error occurred while attempting to access querystring values

Is there a reason why 2 out of the 3 querystring parameters have values, while one is undefined? <li class="@ViewBag.ShowNext">@Html.RouteLink("Next »", "Search", new { page = @ViewBag.NextPage, q = @ViewBag.TextClean, Option = @ViewBag.Option }, n ...

javascript: comparing a specified time to determine if it is within a set time frame

In the process of developing the back-end for a fashion-related application using Node.js, I am faced with the task of indicating whether a particular store is open or closed based on the current time. How can I effectively compare the current time with ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Generating radio buttons dynamically and automatically selecting the correct button using AngularJS

In the questionnaire form, each question is looped over along with its answers to create radio buttons for each answer. The answer object contains a property called answered, which can be true or false depending on whether the answer has been previously ...

How can you make an Angular directive activate only after the scope function in an ng-click handler has been executed?

Scenario I am relatively new to Angular and facing a specific challenge. The goal is to make a directive change the color and add an image to a button. However, I am struggling to get the first if condition to work in my Angular Directive. Issue The ob ...

What is the best way to transmit information using the POST method in JavaScript?

When using javascript, the typical way to redirect a page with a parameter is the following: window.location = "add-new-cos.jsp?id="+id; However, the id value is sent to the next page using the GET method. I am interested in sending it using the POST met ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

What is the best way to create a close button using JavaScript?

I just started learning JavaScript and I want to figure out how to make the close button close the div .popup1 in the following code: https://jsfiddle.net/74hmx0vb/1 <div class='popup1' id="popup1"> <div class="containe ...