AngularJS: Directive not responding to changes in the $watch function

I'm currently developing a real-time websocket application that needs to grab the user's attention whenever there is a change in a value.

The code snippet below is being used in multiple instances on the same webpage:

<span class="badge" animate-on-change animate-class="highlightWarning" animate-watch="totalAnswers">{{totalAnswers}}</span>

and

<div animate-on-change animate-class="colorWarning" animate-watch="rq.answer"
                                 ng-switch="question.type"
                                 ng-repeat="rq in recentResponse.answers"
                                 ng-if="rq.question == question.id">

Typically, 'rq.answer' doesn't change often, but it does update whenever the actual value changes. This behavior works as expected.

However, the first instance doesn't work correctly after the initial call (on page load), even though the visual change for {{totalAnswers}} is displayed. The model is updating, but the $watch function isn't triggered. Any insights into this issue?

.directive('animateOnChange', function ($timeout) {
    return {
      scope: {
        animateClass: '@',
        animateTime: '@',
        animateWatch: '@',
        animateCollection: '@'
      },
      link: function (scope, element, attr) {
        function call() {
          element.addClass(scope.animateClass);
          $timeout(function () {
            element.removeClass(scope.animateClass);
          }, scope.animateTime || 1000); // Can be improved by taking duration as a parameter
        }

        if (scope.animateWatch)
          scope.$watch(scope.animateWatch, function (nv, ov) {
            call();
          }, true);
        if (scope.animateCollection)
          scope.$watchCollection(scope.animateCollection, function (nv, ov) {
            call();
          });
      }
    };
  })
;

Answer №1

In order to properly utilize the $watch method, make sure that the first argument is a function that returns your variable instead of the variable itself:

scope.$watch(function () {
               return scope.animateWatch; }, 
             function (nv, ov) {
               call(); }, 
             true);

For more information on using watch in AngularJS, refer to the documentation.

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

Vue transition isn't functioning correctly without the specified mode parameter of 'out-in'

I'm struggling to comprehend why the transition doesn't smoothly roll from top to bottom without mode="out-in". When using out-in, it rolls as expected (albeit with a delay), but without it, the transition just suddenly appears after rolling dow ...

Identifying the specific filter used in Vue-tables-2

Trying to configure a basic server-side vue-tables-2 with dual filters - one dropdown and the other a search field. The challenge here is identifying which filter was applied within the requestFunction() in order to send a server request. My current strate ...

How to utilize the map function in JavaScript to generate an associative array

I have an array of objects with the following structure [{'list': 'one', 'item': 1}, {'list': 'one', 'item': 2}, {'list': 'one', 'item': 3}, {'list': &ap ...

What is the best way to make a container 100% tall and display a navigation bar?

Struggling to properly render my React page This is what I have: ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router /> </Provider> </React.StrictMode>, document.getEl ...

Break down a string in Javascript into segments of a certain length and save them in a variable

Is there a way to split a JavaScript string into an array of strings of a specified length, where the length can vary? I need to have the length parameter as a separate variable: var length = 3; var string = 'aaabbbcccddd'; var myArray = string. ...

Rebalancing Rotation with Three.js

Currently, I am utilizing Three.js and my goal is to swap out an object in the scene with a new one while maintaining the same rotation as the one I removed. To achieve this, I take note of the rotation of the object I'm removing and then utilize the ...

Compass in Three.js that responds to the rotation of the camera

I have been inspired to create a compass similar to the one featured on Facebook. Take a look at the image here. I have the x, y, and z rotations of the camera and I want to use them to rotate the FOV (the central slice of the compass) in a 2D circle view ...

When using jQuery, the search for the ID within an iframe may fail if the specified condition

I have a scenario where I need to dynamically generate an iframe and its corresponding id. Now, I need to check if the generated id already exists or not. This is what my code looks like: function createIframe(intxnId){ alert("The Id is : "+"$(&apo ...

Is there a way to halt a request that is currently being processed in the backend?

// Search panel with two buttons var searchPanel = new Ext.FormPanel({ frame:true, title: 'Search Criteria', collapsible:true, defaultType: 'textfield', region:'west', autoS ...

Run JavaScript when ColdFusion page is being loaded

Within my ColdFusion page, I have incorporated multiple cfinclude template calls to bring in separate files. Before each cfinclude template call, I am seeking a way to update a javascript variable. I have attempted to achieve this by using: <script typ ...

Exploring the Touch Feature in Angular

I am facing an issue with touch events as I am not receiving any useful X/Y coordinates. The event object does not provide the necessary information I need for touch events (https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches). Despi ...

Can you create a two-dimensional array in JavaScript similar to how it can be done in Java?

To create a board game representation using JavaScript, I am in need of a two-dimensional array. Since I have boards of various sizes, I must initialize the array with the board size at the start. Coming from a Java background, I am familiar with creating ...

I am experiencing difficulties with decoding the JSON in Appengine ProtoRPC

For some reason, I'm having trouble getting the protoRPC API to work on my app-engine. Here is the request I am making: $.ajax({ url: '/guestRPC.get_tags', type: 'POST', contentType: 'application/json', ...

The autosearch feature seems to be malfunctioning

I am currently working on implementing an autocomplete suggestion feature using the AutoComplete plugin from GitHub. I am using a combination of HTML, JavaScript, and CSS for this project. The functionality works perfectly when I hardcode the data in the f ...

Angular's minimum date validation is not accurate for dates prior to the year 1901

Any assistance or clarification on this matter would be greatly appreciated. It appears that there may be an issue with my implementation, as otherwise it seems like a significant bug within Angular. Setup Create a form with a minimum date of 0001-01-01 ...

A simple guide on integrating personalized color palettes into Material-UI Theme

One enhancement I'd like to make in my theme is the inclusion of a custom color called warn import React from 'react' import { MuiThemeProvider } from '@material-ui/core/styles' import createMuiTheme from '@material-ui/core/s ...

Mastering data binding with Vue Js is a process that requires dedication and time

I'm a Vue JS beginner and I've created a component that repeats a grid-like section. However, I've noticed that adding a dropdown in the grid is causing a significant increase in load time. As the number of records grows, the load time will ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

The ng-repeat track by function is not functioning as expected, displaying slow performance and continuing to create $$hashKey

In my code, I have an ng-repeat setup like this: ng-repeat="article in main[main.mode].primary | orderBy: main[main.mode].primary.filter.order track by article.url" The main[main.mode].primary array contains the data and the .filter.order string is used ...

Exploring the integration of Ping Federate with Angular and Web API through Windows Identity Foundation (

I am currently implementing Ping for user authentication in an Angular/.NET Web API environment with WIF. Typically, configuring WIF in the web.config file of an MVC or web Forms application allows for seamless integration, as it automatically intercepts p ...