Issue with child directive not being refreshed after parent directive property modification

This is a follow-up to the following 2 questions:

  1. Passing arguments between parent and child directives
  2. Parent directive controller being undefined when passed to child directive

I have managed to get this part working, but I am facing an issue where the values in the child directive do not update when the value for ng-disabled in the parent directive changes.

You can view an example of this in action on this Plunker link.

Here is the HTML code snippet:

<div ng-app="myApp">
  <div ng-controller="MyController">
    {{menuStatus}}
    <tmp-menu ng-disabled="menuStatus">
      <tmp-menu-link></tmp-menu-link>
      <tmp-menu-link></tmp-menu-link>
    </tmp-menu>
    <button ng-click="updateStatus()">Update</button>
  </div>
</div>

And here is the relevant JavaScript (AngularJS) code:

angular.module('myApp', [])
.controller('MyDirectiveController', MyDirectiveController)
.controller('MyController', function($scope){
  $scope.menuStatus = false;
  $scope.updateStatus = function(){
    $scope.menuStatus = $scope.menuStatus?false:true;
  }
})
.directive('tmpMenu', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
      disabled: '=?ngDisabled'
    },
    controller: 'MyDirectiveController',
    template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
    link: function(scope, element, attrs) {


    }
  };
})
.directive('tmpMenuLink', function() {
  return {
    restrict: 'AE',
    replace:true,
    transclude:true,
    scope:{
    },
    require:'^^tmpMenu',
    template: '<div>childDirective disabled: {{ disabled }}</div>',
    link: function(scope, element, attrs, MyDirectiveCtrl) {
      console.log(MyDirectiveCtrl);

      scope.disabled = MyDirectiveCtrl.isDisabled();

    }
  };
})

function MyDirectiveController($scope) {
  this.isDisabled = function() {
    return $scope.disabled;
  };
}

How can I detect a change in the parent directive and pass it to the child directive without utilizing an angular watcher?

Answer №1

Resolution 1

To address the issue, I have prepared a functional plnkr demo which can be accessed via this link: https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p=preview

The underlying cause of this behavior is that tmpMenuLink retained a copy of the value returned from MyDirectiveCtrl.isDisabled(). Since there was no watcher set up, the solution involved manually monitoring for any modifications and then updating the field accordingly.

scope.$watch(function(){
  return MyDirectiveCtrl.isDisabled();
}, function(){
   scope.disabled = MyDirectiveCtrl.isDisabled();
})

Resolution 2

Another approach, without utilizing watchers, entails passing the reference of an object instead of a primitive type. For example:

$scope.menuStatus = {status: false};

You can view the updated plnkr demonstrating this alternative method here: https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview

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

Ways to incorporate a conditional statement within a dropdown menu

When a user interacts with a dropdown, I want to conditionally show different choices based on their selection. If the user clicks on a checkbox, a specific set of options will appear; if they click on a radio button, another set of options will appear. h ...

Ajax is failing to receive the PHP response

I've been struggling with retrieving values from the database using AJAX during the window load event. When I directly access the PHP script, I see the correct values on the screen. However, when trying to fetch these values through AJAX on another pa ...

What strategies can be employed to streamline the code provided?

Can someone help simplify this JavaScript code for me? I would really appreciate it. Thank you! $(function() { $("#show1").click(function() { $("#showmore1").toggle(); }) $("#show2").click(function() { $("#showmore2").toggle(); ...

Ways to ensure that an HTML form remains filled out even after completing the field, but prior to hitting submit

Scenario: I have found that filling out a form on paper with a pen helps individuals focus more on what they are writing. I am curious if there is a method to replicate this in an HTML form. Desired Interaction: I envision a scenario where a person select ...

Utilizing the React useMemo Hook in Practical Examples

Scenario After delving into the official documentation for hooks, I decided to experiment with useMemo in one of my projects. To test it out, I created a sandbox project which can be accessed here. The example involves running an expensive calculation e ...

Utilizing multiple criteria to filter through a nested array

I am faced with an array structured as follows const treeObj = [ { id: 1, name: 'Section One', items: [ { id: 1, name: 'Section One Item One' }, { id: 2, name: 'Section One Item Two' }, ...

Anticipated worth following the setTimeout function has been established

When trying to set the expected value in a setTimeout function, I encountered an issue. The two values I have are: const first = 0; const second = 0; However, this resulted in an error: "Uncauth TypeError: You provided 'undefined' where a strea ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Service failure occurs due to the inability to inject a factory

I've been working on an angular seed project that includes services and a factory. Specifically, my companyService relies on a factory named company. However, I've encountered an issue when trying to inject company into companyService, resulting ...

ES6 AngularJS 1: The Power of $inject and Inheritance

I am facing a situation where I have 3 child controllers that extend a shared parent controller. The structure looks like this: class ParentController { constructor( $scope, $state ){ this.$scope = $scope; this.$state = $state; } } ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

Execute JavaScript code inside lightSlider

I'm attempting to incorporate a jQuery UI date picker into a lightSlider item. However, I'm struggling to understand how to make JavaScript execute within the slider based on its content. The date picker is just one example of what I'm tryin ...

What is the correct way to declare this and assign values afterwards? (javascript)

I am having trouble with this code and I can't figure out how to properly declare it. var input = { container: '.slide_container', container_all: '.slide_show', slides: [] }; var $slides = $(&a ...

Extract the value of an HTML tag and assign it to a variable

Can someone help me out with this, as I am not very familiar with Smarty: When I use ajax to submit this form: <form accept-charset="UTF-8" method="post" onSubmit="return validate()"> <input type="text" name="code" maxlength="15" class=" ...

Tips for handling arguments in functional components within React applications

Is it possible to pass arguments to a function in a functional component without creating the function directly in JSX? I've heard that creating functions in JSX is not recommended, so what's a better way to achieve this? function MyComponent(pr ...

The combination of MUI CardContent and flexBox seems to have issues when used in conjunction with typography and chips

Take a look at this React code using MUI. It's designed to create a Card that showcases Character Information. const CharacterPreview = ({ characterKey }: CharacterPreviewProps) => { return ( <Card sx={{ maxWidth: 256, borderRadius: 4 }}&g ...

The 3D formula for calculating the distance between a point and a line

Can anyone provide me with a computer program or algorithm that calculates the distance between a point and a line in a three-dimensional space? The program can be written in JavaScript or any other programming language. In this scenario, P represents th ...

Guide to integrating custom AngularJS directives into the html validator in Netbeans 7.4 IDE?

After making the switch from Eclipse to Netbeans 7.4 IDE, I am looking for a way to incorporate custom Angular directives into the html validator. If you include the following code in your html file: <div> <my-directive></my-directive& ...

Using AngularJS forEach to assign properties to objects within a found set in ng-repeat

I am using an ng-repeat to display items from a JSON file, and they can be filtered based on user input. <tr ng-repeat="i in filteredItems = (iso3166 | filter: {alpha_2: isoQuery})"> Everything is working as expected. Each item in the "iso3166" gro ...