Using AngularJS - Injecting a variable into a directive's callback function

I need help with passing arguments from my directive to the caller. I've been struggling to make it work.

Currently, I am able to call the function without any arguments successfully. However, when I try to pass arguments, it stops working:

Here is the link to the Plunker: (http://embed.plnkr.co/autsgiBlWjz8cX2BL6Sj/preview)

To give you a better understanding, here is the code snippet:

// Code goes here angular .module('myApp', []);

angular
  .module('myApp') 
  .directive('myDirective', myDirective)
  .controller('ParentController', ParentController);  

function myDirective() {
  return {
    restrict: 'E',
    controller: {},
    controllerAs: 'vm',
    bindToController: {
      myCallback: '&'
    },
    scope: {},
    template: '<div><button data-ng-click="myCallback({msg:123})Call Callback</button></div>'
  };
}

function ParentController() {
  var self = this;

  self.parentCallback = parentCallback;

  function parentCallback(args) {
    alert('The message is: ' + args.msg);
  }
}

HTML content below:

  <head>
    <script data-require="angular.js@*" data-semver="2.0.0-alpha.45" src="https://code.angularjs.org/2.0.0-alpha.45/angular2.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div data-ng-app="myApp" data-ng-controller="ParentController as ctrl">
      <my-directive my-callback="ctrl.parentCallback(args)"></my-directive>
    </div>
  </body>

</html>

Answer №1

Referencing information from the angular documentation

Sometimes, it is necessary to pass data from an isolate scope through an expression to the parent scope. This can be achieved by providing a map of local variable names and values within the expression wrapper function. For instance, consider the hideDialog function which indicates a message to display when concealing the dialog. In the directive, this is denoted by invoking close({message: 'closing for now'}). Consequently, the local variable message will then be accessible within the on-close expression.

If you wish to receive args in a similar manner, the template of <my-directive> should resemble the following example.

<div><button data-ng-click="myCallback({args: {msg:123}})">Call Callback</button></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

Generate a JavaScript variable in real-time and leverage it to retrieve the corresponding JSON response

After receiving a JSON response from an API as depicted in the image below: https://i.sstatic.net/5eq43.png I encountered an issue where the same column_code is used in both the variable_meta section and the data part of the response. This column code act ...

Is there a way to emphasize my navigation using a call-to-action (CTA)?

My CTA is set up like this: <div class="heading__link"> <a class="heading__cta" href="#about">View my work</a> </div> Additionally, my navigation bar is structured like this: <nav id=&quo ...

Is it possible to set the input form to be read-only?

I need to create a "read-only" version of all my forms which contain multiple <input type="text"> fields. Instead of recoding each field individually, I'm looking for a more efficient solution. A suggestion was made to use the following: <xs ...

Creating a custom loading spinner featuring your logo

Hello, I am looking to create a custom loading spinner using CSS, JS or any other method with my logo. I have the logo in PNG, GIF, and SVG formats and would like to use it for long site loads, image loads, or any other loading processes within my Vue3 pro ...

Prevent the Button from causing the Aspx Page to refresh

I've been working on a JavaScript function for my website that displays a popup when a button is clicked. However, every time I click the button, the webpage reloads causing the popup to disappear. Is there a way to prevent the page from refreshing wh ...

What is the best way to trigger the second function on a click event?

Is there a way to trigger my 20 second timer with the click of a button, followed by an alert after the timer ends? HTML <aside class="start-box"> <button type="submit" class="btn btn-primary btn-lg" id="toggleBtn" onclick="startCloc ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

How to visually represent options without labels using icons in Material UI Autocomplete

My options are structured as follows: const options = ['option1', 'option2']; I am looking to display the options with icons like this: https://i.stack.imgur.com/aubHS.png The current code for rendering options looks like this: ...

Issue: ENOTDIR - The specified path './commands/setWelcome.js' is not a directory

I've been working on developing a moderation bot, but I keep encountering an error that claims I don't have commands and a setWelcome file in my project even though they are present. The error message reads as follows - node:internal/fs/utils:344 ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...

Attempting to utilize a for loop in JavaScript to condense code, however encountering a "not defined" error

I'm relatively new to working with javascript and currently attempting to enhance the following code snippet (which has been tested and is functioning correctly): // snail 1 // var s1 = document.createElement("div"); s1.id = snail1.id; s1.className = ...

Issue with timebox filtering in customapp.js for Rally SDK 2

I am interested in creating a timebox filtered app and found an example at However, when attempting to run this on a custom HTML page, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) on th ...

Pause and Persist

Can someone help me clarify a code issue I'm facing? I have a piece of code that checks an array for overlapping values based on different criteria. This code specifically deals with rows and columns in a Google Sheet using GAS. Here's what I cur ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

What is the best way to set a CSS background using vue-cli 3?

What is the process for setting a CSS background in vue-cli 3? I have set my vue.config.js like this. Is publicPath properly configured? JavaScript const path = require("path"); module.exports = { devServer: { port: 8081, overlay: { warni ...

Designing a flawless CSS pattern for the online world

Currently, I am working on creating a seamless CSS pattern for the web. Even though this may seem impractical and nonsensical, I find joy in experimenting with it. View my progress here After successfully designing my first tile, my next challenge is to ...

Choose a single conditional element by using the .each method in JavaScript

I am looking to choose just one article that meets a specific condition. In my code, I am using hourDiff==0 as the condition to be true. I am using the 'each' function to loop through the articles. I have set display:none for all articles in the ...

Checking for the existence of a variable retrieved from the API in AngularJS

On the api side, I am receiving a json metadata object with image properties. To test for the existence of a property, I am using angularJS, coffeescript, and haml for the views. Below is the JavaScript code that fetches the data: getImages = -> l ...

Implementing a file download feature in Python when clicking on a hyperlink

I'm attempting to click on the href link below. href="javascript:;" <div class="xlsdownload"> <a id="downloadOCTable" download="data-download.csv" href="javascript:;" onclick=&q ...

Combining each function in Google Sheets script with the && operator allows for setting a range of values to compare against the array

Looking for help with a coding issue involving checking data format before running specific code. I've successfully implemented checks to prevent sending duplicate or empty data, but now I'm struggling with validating that the data is in the cor ...