Transfer the controller of the parent directive to a directive controller, similar to how it is executed in the "link" function

In the structure of my directives, there is a need for one directive to have functions in its controller so that child elements can interact with it. However, this directive also needs access to its parent directive's controller. I am unsure of how to achieve this within the controller itself (I know how to do it in the "link()" function, but this time I require the use of the controller for child interactions). It should be achievable using scope:

controller: function($scope){},
link: function (scope, ..., parentCtrl){
    scope.parentCtrl = parentCtrl;
}

However, I find this method confusing, as the link function is executed after the controller. Is this an acceptable approach? I am uncertain and worried that it may not be a good design choice.

Visual representation:

ParentParentDirective
    controller: function(service){
        this.service = service;
    }

ParentDirective
    controller: function(){
        this.callOnService = function(id){
            ???ParentParentDirective???.service.callSth(id);
        }
    }

ChildDirective
    link(scope, ...,ParentDirectiveCtrl){
        scope.makeChanges = ParentDirectiveCtrl.callOnService;
    }

Answer №1

To achieve this, you can utilize the $element.controller method like in the following example.

angular.module('app', []);

angular.module('app').directive('grandparent', function () {
  return {
    restrict: 'E',
    controller: function () {
      this.go = function () {
        console.log('Grandparent directive');
      };
    }
  };
});


angular.module('app').directive('parent', function () {
  return {
    restrict: 'E',
    controller: function () {
      this.go = function () {
        console.log('Parent directive');
      };
    }
  };
});

angular.module('app').directive('child', function () {
  return {
    restrict: 'E',
    require: ['^parent', '^grandparent'],
    controller: function ($element) {
      var parentCtrl = $element.controller('parent');
      var grandparentCtrl = $element.controller('grandparent');
      
      parentCtrl.go();
      grandparentCtrl.go();
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="app">
  <grandparent>
    <parent>
      <child></child>
    </parent>
  </grandparent>
</div>

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

Distinguishing between a save and update using a shared Angular JS template

Currently, I am engaged in a project that involves a PHP backend and Angular 1.x on the front end. Within this project, there is a Listings model used in conjunction with a common template for both adding and editing Listings. The challenge lies in distin ...

Encountering a problem with configuring webpack's CommonsChunkPlugin for multiple entry points

entry: { page1: '~/page1', page2: '~/page2', page3: '~/page3', lib: ['date-fns', 'lodash'], vendor: ['vue', 'vuex', 'vue-router'] }, new webpack.optimize.C ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

Adjust CardMedia Images to match their content in the new MUI 5 version

I’m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...

Issue with Firebase Cloud function not terminating despite receiving a 204 response code

Currently, I am developing a cloud function to manage server operations for a gaming panel. Everything seems to be functioning correctly except that after the request is completed, it fails to trigger the expected "data", "end", or "closed" events which ...

Is there a way to see the countdown timers in Angular 7?

Is there a way for me to view my timer's countdown as it starts? I have attempted to bind it to a variable, but all I see is [object Object]: setTime(time) { if (this.settime >= 5 ) { this.currentTime = time; this.alerttime = thi ...

When attempting to access a PDF file via URL, binary information is visible on the browser instead

I'm currently developing a Java application and facing an issue with opening PDF files in a web page using both IE and Chrome. After extensive research and attempts using the JSoup API, here is the complete process from HTML to Java controller to disp ...

Is it possible for JavaScript to interface with MySQL databases?

Is it possible to establish a connection between JavaScript and MySQL? If yes, what is the process? ...

Issue encountered while retrieving JSON data from Github

I am currently using d3.json to retrieve a JSON link from the Enterprise GitHub (within the same repository/folder as the JavaScript file). d3.json("https://raw.github.exampleEnterprise.com/path/to/repo/data.json?token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ...

Struggling to synchronize the newly updated Products List array in zustand?

Let me clarify the scenario I am dealing with so you can grasp it better. I have a Cart and various Products. When a user adds the product (product_id = 1) twice to the cart with the same options (red, xl), I increase the quantity of that item. However, i ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

How can you remove the add button in React Material Table?

Within the material table, there is a feature that allows for the conditional hiding/disabling of action buttons. Is there a way to do the same for the Add button located at the top of the table? See screenshot below ...

Is there a way to use JavaScript or jQuery to identify if Firefox is blocking mixed content

Is there a way to detect when Firefox (or any browser) is blocking mixed content using JavaScript or jQuery? To learn more about Firefox's mixed content blocking feature, visit: The backstory: My company has an external vendor that handles the onli ...

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

What is the best way to retrieve an object in Angular from JSON data?

After sending an AJAX request to a PHP server, I receive a JSON object: lang: {news feed: "lenti"} Upon trying to display the text from the object in my template using: $scope.data = response.data, {{data.lang.news feed}} I encounter an error in the c ...

"Troubleshooting: Fixing the 'Firebase Cloud Function admin reference is not a function'

I recently attempted to transform the .WriteOn cloud function in my Firebase app into a scheduled cloud function. The goal was to create a function that would run every 4 days to delete messages older than 2 days. While this worked well for the .WriteOn fu ...

Managing interactions with dynamically created buttons

Our Story Greetings! I am skilled in C# and VB.net, but I am diving into the world of Javascript and React. Currently, I am building a ticket purchase app to enhance my skills. While I was able to quickly create this app using Angular, React has posed mor ...

How to create a floating <Toolbar/> with ReactJS, Redux, and Material-UI

Can anyone help me figure out how to make a toolbar floatable when scrolling down using Material-UI? I tried setting textAlign:'center', position: 'fixed', top: 0, but it's resizing strangely when applied to the <Toolbar/>. ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...