The watch functionality is failing to work within a specialized attribute directive that is being utilized within a separate custom element directive

I'm currently working with two directives that handle separate functionalities. I am attempting to utilize the attribute directive within an element directive, but I'm encountering issues with the watch function not working on the attribute directive. You can find the code example on jsfiddle here: http://jsfiddle.net/hsyR5/8/

My goal is to have the isLoaded directive's watch function triggered whenever the value of the is-loaded attribute changes.

HTML:

<div ng-app="myapp">    
    <div ng-controller="ReportCtrl">
        <mydir is-loaded="false" id="change" expand-me="isExpanded" ng-transclude>
            <button ng-click="expandIt()"> Expand</button>
        </mydir>
    </div>

Javascript code:

var myApp = angular.module('myapp', [])
myApp.directive('mydir', function () {   
    return {
        restrict: 'E',
        scope : {
            expandMe:'='
        },
        replace: true,
        transclude: true,
        template : "<div></div>",
        link: function (scope, element, attrs) {
            scope.$watch('expandMe', function (){
                //load the data
                console.log('inside mydir directive');
                element[0].attributes['is-loaded'].nodeValue = ''+scope.expandMe;
            });
        }
    };
});

myApp.directive('isLoaded', function () {
    return {
        restrict : 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.isLoaded, function (){
                console.log('isLoaded Changed');
            });
        }
    };
});

myApp.controller('ReportCtrl', function($scope){
 $scope.isExpanded = false;
  $scope.expandIt = function(){
      $scope.isExpanded = !$scope.isExpanded;
  }
})

Answer №1

When using scope.$watch, it is important to note that if you pass a string as the first argument, it must correspond to a scope property.

For example, attempting to watch for a non-existent property would be like:

scope.$watch("false", function (){
     ....
});

In this case, scope.false is undefined.

If you are not watching a specific scope property, you can use a function that returns a variable to monitor as the first argument:

scope.$watch(function (){
     return attrs.isLoaded;/* define what to watch*/
}, function(newVal, oldVal) {
      if(newVal != oldVal){
           console.log('isLoaded Changed');
      }
});

An alternative to using $watch on scope is utilizing attrs.$observe:

In the initial directive, there is no need to access element[0].attributes since the attributes are already available as arguments of link. To modify an attribute, simply do:

attrs.isLoaded = '' + scope.expandMe;

DEMO

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

Pattern matching using regex can also be used to restrict the number of characters allowed

Having some trouble with regex to match a specific pattern and also limit the number of characters: Let's say I have allowed number prefixes: 2, 31, 32, 35, 37, 38, 39, 41, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 I only want numb ...

A guide on using Jest.js to test labels within Vue 3 Quasar components by utilizing a forEach loop

Within my Vue Quasar component, a badge is implemented as shown below: <q-badge :color="green" text-color="white" :label="`${value.toFixed(2)}%`" /> The corresponding script is structured like this: <scri ...

Should the Express.js router be required directly or stored in a variable before use?

I've been pondering a performance question related to express.js. In my server.js file, I have all the routes defined and the child routes are imported as follows: const ROUTE__FOO = require('./routes/foo') const ROUTE__BAR = require(' ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

Node: Sending JSON Values in a POST Request

I am currently working with the index.js file below: var Lob = require('lob')('test_6afa806011ecd05b39535093f7e57757695'); var residence = require('./addresses.json'); console.log(residence.residence.length); for (i = 0; i ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...

Exploring the functionality of a Vue component designed solely through a template

I currently have a basic Vue application set up: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'& ...

Update a section of my PHP webpage using setInterval()

How can I refresh a PHP value every second using setInterval()? I am familiar with refreshing values in HTML, but now I want to do the same with PHP values. Here is my code: <script> setInterval(function() { <?php $urlMachineOnline = ' ...

Customizing Images using a JSON array of images

Looking to implement a feature that displays images fetched from a CMS via a JSON file. The JSON data structure is as follows: { "images": [ {"title": "Image One", "url": "image1.jpg"}, {"title": "Image Two", "url": "image2.jpg"}, {"title": "Ima ...

Confirming angular 1.x input checkbox

In my code, I have an angular 1.x checkbox set up like this: <input type="checkbox" name="fooName" id="fooId" ng-model="false" > When I use jQuery to do the following: $("#fooId").val() I always receive "on" as the output. The same result oc ...

Retrieving Angular URL Parameters Containing Slashes

I'm currently in the process of developing a single page angular application. This app retrieves a token from the URL and then sends it to an API. At the moment, my URL structure is as follows: www.example.com/?token=3d2b9bc55a85b641ce867edaac8a9791 ...

I am encountering problems with images that are imported as module imports in a Vue.js project

Currently, I have stored all the default images for my Vue project in a designated folder. The path to this folder is web/images/defaults/<imageNames>.png. Instead of importing each image individually in my components, I wish to create a file that co ...

What measures can be taken to safeguard this hyperlink?

Is there a way to conceal HTML code from the source code? For instance: jwplayer("mediaplayer").setup({ file: "http://example.com/Media.m3u8", autostart: 'true', controlbar: 'bottom', file: "http://exa ...

What is the best way to create a toggle effect for a <nav> bar that appears from beneath a div?

I need assistance with a navigation setup where the nav (located inside the header) needs to be connected to the bottom of a div named .menu_bar. The desired behavior is for the nav to slide down from directly underneath the .menu_bar when toggled, but cur ...

The complete page gets re-rendered when Nuxt child routes are used

When I attempt to utilize child routes, my goal is to maintain specific data on the page while modifying other content. To illustrate this concept, I have created a straightforward example available at this link. After selecting "cat" and increasing the ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

What is the best way to patiently wait for a promise to fulfill, retrieve its value, and pass it to another function?

I am facing an issue with getting the value of stringReply into my app.post method in Express. From what I understand, it seems like the code is fully executed before the promise is resolved, resulting in an undefined value when attempting to log stringR ...

Why doesn't ng-init work in AngularJS?

I encountered a parse error Syntax Error: Token '{' is an unexpected token at column 8 of the expression [user= ${user}] starting at [{user}]. home.html <body ng-controller="mainCtrl" ng-init="user= ${user}"> In this instance, I am att ...

The onclick functionality is not functioning properly within email communications

My JavaScript code contains an AJAX call within Datatables, and this snippet of code is causing an issue: { "data": null, "width": "10%", "render": function(data){ icon2 = '<center><button type="button" class="btn btn-info ...