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

Struggling to access FormData in php

I'm having trouble retrieving variables from FormData in PHP after making an AJAX call. What could be causing this issue? Here is the snippet of my JavaScript code: var sendData = new FormData(); sendData.append('itemid',$('select#sel ...

Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string txt = "Local residents o1__have called g__in o22__with reports..."; that requires extracting numbers between each occurrence of o and __ If we use the following regex: txt.match(/o([0-9]+)__/g); We will obtain ...

Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex: posts:[ { id: 1; title: "Place", acf: { address: { state: "Arkansas", ...

All elements in the array are being simultaneously updated with the same value in React

I am encountering an issue with my code. Whenever I draw rectangles by clicking and dragging, the new rectangle added to the array overwrites all previously stored rectangles. For example, if my array (named data) initially contains Rectangles as - [Rect ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Next.js does not support Video.js functionality when using server side rendering

I'm struggling to set up video.js in my next.js project and encountering issues. When the player is loading, it initially appears black and then disappears abruptly. A warning message in the console reads: "video.es.js?31bb:228 VIDEOJS: WARN: T ...

I am puzzled as to why it is searching for an ID rather than a view

Currently, I am attempting to navigate to a specific route that includes a form, but for some unknown reason, it is searching for an id. Allow me to provide you with my routes, views, and the encountered error. //celebrities routes const express = requir ...

Styling an active link in Next.js using Styled Components

Looking for a way to customize the active link style using styled components. I have a navigation bar where the currently active link should have a specific style applied. Any suggestions are appreciated! import React from 'react' import Link f ...

Manipulating HTML attributes with Jquery's attr() method results in returning [object Object]

Despite reading numerous articles and questions, I have yet to find a solution. My PHP page is designed to update an easypiechart using AJAX with database values checked every X minutes. For demonstration purposes, I have set the update interval to 10 seco ...

having difficulty sending the username and password from the HTML page to the controller in AngularJS

In my AngularJS controller, I am having trouble retrieving the values of the username and password fields after submitting the login form. Here is the HTML code for the form: <form class="form-signin" action="" method="post"> ...

What is the best way to retrieve data based on a condition using JavaScript within a React application?

I am struggling to load only a specific number of rows that meet a certain condition. Unfortunately, the current code is fetching all 25 rows and the condition is not being applied correctly. If anyone could provide assistance, it would be greatly apprec ...

Compilation unsuccessful. The LineGraph.js module could not be located due to recursion in resolving

After successfully installing react-chartjs-2 and chart.js using the command npm install --save react-chartjs-2 chart.js, I encountered an error when attempting to use LinkGraph: Failed to compile. ./src/LineGraph.js Module not found: Recursion in resolvi ...

"Optimizing npm packages for front-end web development in vanilla JavaScript: A guide to bundling for production deployments on

My website is built using vanilla HTML/CSS/JavaScript with ES6 modules and can be deployed to GitHub pages and Netlify. I have set up my site by importing "main.js" in my HTML like this: <script src="js/main.js" type="module" defer&g ...

Testing URL Parameters in JEST with an API

Seeking integration tests using Jest for an API endpoint. Here's the specific endpoint: http://localhost/universities/ucla/class/2013/studentalis/johndoe. When tested with a put request, it returns 201 on Postman. However, the testing encountered a t ...

Restricting the number of times a user can click on

I am currently displaying a table with data obtained from a database query. The structure of the table is outlined below: <table id="dt-inventory-list" class="table table-responsive"> <thead> <tr> <th>Field ...

The functionality of the Angular directive ngIf is not meeting the desired outcome

We are currently working on transferring data from one component to another using the approach outlined below. We want to display an error message when there is no data available. <div *ngIf="showGlobalError"> <h6>The reporting project d ...

Tips for displaying XML content within an AngularJS application using HTML

I have a string containing data: var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel> </rss>" ; My goal is to display this string on a web page in the proper XML format. <channel& ...

Showcase text in a straight row by utilizing ng-repeat and bootstrap

My goal is to show each word on a new line, similar to how words are displayed in a hangman game. The words should be displayed as blanks. <body ng-init="models = [['H','a','p','p','y'],['X',& ...

Incorporating database coordinates into Marker React Leaflet: A Step-by-Step Guide

When I retrieve coordinates from the database, they are structured as "lat" and "lon" fields. In my mapping application, I have multiple markers to display. How can I combine these two fields to pass coordinates (coord.lat and coord.lon) to the Marker comp ...

The if-else statement is providing a misleading outcome

While working on my map using leaflet, I decided to implement a dynamic color concept based on input data. However, despite comparing 3 sets of data to ensure accuracy, some parts of the color scheme are displaying incorrect results. Below is the snippet o ...