Callback function with an angular directive nested inside

Within my list directive (which is essentially a table), each element contains a tools directive with select, edit, and delete buttons. The tools directive has callbacks for each action so that a specific controller can handle each action separately. However, I am unsure of how to pass the selected item to the controllers callback function. Any suggestions on how to achieve this?

The tools directive:

Javascript: Define the callbacks here

app.directive('itemTools', function() {
return {
  restrict: 'AE',
  transclude: true,
  scope: {
    item: '=',
    selectCallback: '&',
    editCallback: '&',
    deleteCallback: '&',
    cloneCallback: '&',
    activateCallback: '&',
    deactivateCallback: '&',
  },

  link: function(scope, element, attr) {

  },
  templateUrl:'templates/common/item.tools.html',
  controller: function($rootScope, $scope) {
  }
}

});

HTML:

<div>
 <button ng-click="selectCallback({id: item.id})">
 </button>
 <button ng-click="editCallback({id: item.id})">
 </button>
 <button ng-click="deleteCallback({id: item.id})">
 </button>
 <button ng-click="cloneCallback({item: item})">
 </button>
 <button ng-click="activateCallback({item: item})">
 </button>
 <button ng-click="deactivateCallback({item: item})">
 </button>
</div>

The list directive: These callbacks are further processed by the item-tools directive

app.directive('moduleList', function() {
return {
  restrict: 'E',
  scope: {
    modules: '=',
    selectCallback: '&',
    editCallback: '&',
    deleteCallback: '&',
    cloneCallback: '&',
    activateCallback: '&',
    deactivateCallback: '&',
  },
  templateUrl:'templates/module/module.list.html',
  controller: function($scope) {

  }
}

});

HTML:

<table class="table table-responsive">
  <tbody>
    <tr ng-repeat="item in items | orderBy:orderByField:reverseSort">
      <td class="text-center">
        SOME DATA OF THE OBJECT....
      </td>
      <td>
        <item-tools
        item="item"
        select-callback="selectCallback({id: item.id})"
        edit-callback="editCallback(item.id)"
        delete-callback="deleteCallback(item.id)"
        clone-callback="cloneCallback(item)"
        activate-callback="activateCallback(item)"
        deactivate-callback="deactivateCallback(item)">
        </item-tools>
      </td>
    </tr>
  </tbody>
</table>

I have successfully triggered the controllers function, but am struggling with how to pass in the selected item itself.

Appreciate any help!

Answer №1

In order to establish a connection between child directives and their parents, the parent directive controller needs to be assigned to the child:

// parent directive
app.directive('parentDirective', function() {
    return {
        controller: function() {
            this.greet = function() {
                return 'Greetings from the parent';
            };
        }
    };
});

// child directive
// By using ^ctrlName in the require attribute, you can access the parent controller
app.directive('childDirective', function() {
    return {
        require: '^parentDirective', // specify the need for the parent controller
        link: function(scope, element, attrs, ctrl) {
            // Now you can utilize the methods of the parent controller
            ctrl.greet(); // returns 'Greetings from the parent'
        }
    };
});

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 create interaction between two web pages with JavaScript

I am attempting to design a webpage where one page can influence the content of another page. I have two HTML pages and a JavaScript file named "Controll.js" which contains a function that changes the content of "Indiv" in Index.html. This function is tr ...

The basic evaluation of jQuery elements does not result in a comparison

Wondering what's going wrong in this code: employee_ids = $('[data-employee_id="'+employee+'"]'); timestamp_ids = $('[data-scheduled_on="'+timestamp+'"]'); var common = $.grep(timestamp_ids, function(element) ...

Whenever I try to open my jQuery UI Dialog without first displaying an alert, it does not work

Beginning of my HTML page, initializing a dialog : <script type="text/javascript"> $(function() { $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: true, height:180, width:300, modal: true, buttons: { "Yes": ...

Decoding JSON data in AngularJS

A json object has a key named lastLogin which holds a string value. I am attempting to display the names John and Blake. $scope._users = [{ "User": { "userid": "dummy", "lastlogin": "{\"employees\":[{\"first ...

"Exploring the Differing Approaches of Ajax: Constructing

Considering StackOverflow's recommendation to ask a question rather than start a discussion, let's explore two methods using HTTPAsyncRquest to update a webpage without refreshing it: 1) Parsing/interpreting data returned by AsyncRequest to buil ...

Tips on successfully executing the swap method in the JustSwap smart contract

I'm attempting to finalize the JustSwap-contract S-USDT-TRX Token (TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE), but I keep receiving a "REVERT opcode executed" response in the console. My code: const TronWeb = require("tronweb"); const ethers ...

Performing HTTP requests within the routes of a Node.js application

I am in the process of creating a dynamic slideshow that automatically pulls images using a specific tag from Instagram. To achieve this, I need to connect to the Instagram API and obtain an access token by making a call to their authorization URL. Utilizi ...

Having trouble retrieving the data from the second child object in an object returned by an API call in a

Having trouble accessing the second child object of an object generated by an API response. The weather API in question can be found at . Refer to Display.js for a detailed explanation. App.js import React,{useState} from 'react'; import Navbar ...

Loading a new view within AngularJS using the ng-view directive opens up a fresh

I am currently working on integrating Angular with a REST API for the login process. After successfully setting up Angular with my REST calls, I aim to redirect to a new page upon successful login. In my success handler, I have implemented the following ...

Why does Axios keep timing out despite successful testing in Postman?

Trying to set up a single request for my app using axios with express/node js. Here is the code snippet that was generated through the Postman app. I have attempted different variations by creating my own form, but I always end up with the same result. co ...

Preserving the status of altered DOM elements across different pages

Hey there, I've successfully created a vertical menu with jQuery slideUp and slideDown functionalities. The menu is working smoothly, but now I'm looking for a solution to keep its state after a postback. For example, if a user clicks a button c ...

Resource Jump.js could not be loaded

Although I am still new to NPM, I have mostly built websites without using it. Recently, I decided to implement smooth scroll using Jump.js. Initially, everything seemed to work well when I used the live server extension in VScode. However, once I uploade ...

How can I use JavaScript to display every line individually in a textarea?

I am trying to display the content of a textarea in my div with the ID #result. I want to maintain the line breaks from the textarea and append 1 at the end of each line. Here's my current attempt, but it only adds 1 to the last line. <!DOCTY ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Enable a button or class to dynamically alter its color

Hi there! I'm new to coding and just started learning HTML and CSS. My question is: How can I change the color of buttons once they are clicked? <div class="icon-bar"> <a href="#"><i class="fa fa-search" ...

What are the distinctions between Electron's built-in module and the one obtained through npm? And what is the method for accessing the electron object from external modules?

Electron Documentation If you refer to the official Electron installation guide, it recommends installing Electron using the following command: npm install electron --save-dev Following these instructions, I proceeded with the installation. However, upo ...

Ensuring that jQuery(document).ready(function() contains the appropriate content

Recently, I've been attempting to integrate a javascript gallery into my WordPress site. However, I'm encountering some confusion regarding what needs to be included in the .ready(function) to successfully run the gallery. The original jQuery fun ...

Angular JS is experiencing difficulty retrieving the passed value in the directive

While attempting to develop a custom calendar in AngularJS, I encountered an issue with passing values to the isolated scope within the directive. Despite my efforts, I am unable to access these values on the directive's scope and I am struggling to u ...

To enable communication between methods, you can easily add a property to a JavaScript class component

Is there a better way to communicate between methods in a class? class T extends React.Component { constructor(props) { super(props) this.a = false; } methodA { //will set 'a' in this method, maybe async. } ...