How can a callback be created in an Angular directive using a function name stored in the parent scope variable?

Currently, I am experiencing an issue with a parent scope that has a function name defined within a variable.

$scope.form.callback = "sayHello(msg)";
$scope.sayHello = function(msg) {
    alert('Parent says ' + msg);
};

The parent template is structured like this:

<a sg-dir sg-callback="{{form.callback}}" href="">Click Me</a>

Below is the code for "sgDir":

someModule.directive("sgDir", function(){
    return {
        scope: {
            sgCallback: "&"
        },
        link: function(scope, elem, attrs, ctrl) {
            scope.sgCallback({msg:'Hello world!'});
        }
    };
});

However, this setup is resulting in an error message:

[$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the
expression [{{form.callback}}] starting at [{form.callback}}].

Please assist me with resolving this issue.

Update:

I need to keep the function name within a variable as per my requirements.

Answer №1

You made a syntax error, resulting in a parsing issue. To correct this, ensure that you pass the actual function sayHello on the isolated scope attribute instead of an interpolated function reference.

For example, use sg-callback="form.callback(msg)" where the parameter msg will be filled by the directive when calling the callback function (as seen here:

scope.sgCallback({msg:'Hello world!'})
).

<a sg-dir sg-callback="sayHello(msg)" href="">click Me</a>

Check out the demo here

Update

The preferred method to pass a callback function to a directive is using &. However, if you need to pass a dynamic string that will be evaluated within the directive, you can follow a workaround. Pass a string expression as an attribute value and change the sgCallback to sgCallback: "@" in the directive's isolated scope. Then, replace the string with the actual parameter value upon clicking the anchor element.

Note that the current implementation involves accessing the parent scope using scope.$parent to evaluate the function expression against the parent controller scope. If there is no isolated scope in the directive, you would use scope.$eval instead of scope.$parent.$eval.

sgDir

.directive("sgDir", function($timeout) {
  return {
    scope: {
      sgCallback: "@"
    },
    link: function(scope, elem, attrs, ctrl) {
      elem.on('click', function() {
        $timeout(function() {
          var callback = attrs.sgCallback.replace('(msg)', '(\''+ "Hello World" +'\')');
          scope.$parent.$eval(callback);
        });
      });
    }
  };
});

View the updated Plunkr

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

Change the way a button interacts with a different element

Currently, I am utilizing SlickSlider from http://kenwheeler.github.io/slick/ and attempting to integrate the Next and Prev buttons with other elements (specifically spans within another container). I have attempted the following: $('button.next&apo ...

I am encountering a confusing issue where utilizing await does not actually wait for a Promise to resolve. Can you shed some light on why this unexpected behavior is happening?

Here is a function that I am working with: const getCurrentDetails= async () => { const currentDateTime = new Date(moment('00:00','HH:mm') .tz('America/New_York') ...

React does not display newly updated states when they are modified

React does not trigger a re-render on the screen when updating the state and the useEffect hook is not invoked either. https://i.sstatic.net/YsA22.gif After clicking the "change" button, React fails to update with the new values and the useEffect hook re ...

Numerous Kendo windows are layered on top of each other, yet the text divisions within them remain distinct

I am currently working on a project that involves laying out multiple Kendo windows in rows. Specifically, I need to display 4 windows in each row and have them shift left when closed. My framework of choice is Bootstrap 3. Everything works as expected w ...

Retrieving the user's Windows username with JavaScript

Is it possible to retrieve the Windows user name solely in Internet Explorer using the code below? function GetUserName() { var wshell = new ActiveXObject("WScript.Shell"); alert(wshell.ExpandEnvironmentStrings("%USERNAME%")); } What methods ...

Is there a way to improve this code without the need for the variable `a`?

Assist in enhancing the performance of the functions below, without using the variable a getFieldsGroups(){ let list = []; if(this.activeTab.fieldsGroupName === ''){ this.activeTab = { groupIndex: 0, subgroupIndex: 0, f ...

Discover the best way to utilize Ember Data serializer in conjunction with JQuery AJAX requests

I have utilized Ember-Data effectively with API endpoints structured as follows: domain.com/apples/ => displays a list of apples domain.com/apples/1/ => shows details for Apple with id 1 domain.com/worms/ => lists all the worms N ...

What could be causing the syntax error I'm encountering while trying to extract data from this JSON file?

I've been encountering a syntax error in my console that reads "Uncaught SyntaxError: Unexpected token '}'. I've checked my JavaScript code, but being new to coding, I'm not sure why this is happening. Could the error be on the JSO ...

What is the best method for passing parameters from HTML to AJAX within code?

My project involves working with Flask, HTML, and Ajax. Here is the HTML code snippet: <script type=text/javascript> $(function() { $('a#calculate').bind('click', function() { $.getJSON('/_add_numbers&ap ...

What is the best way to enable a link upon clicking while simultaneously disabling the others using JavaScript?

When I click on a link, I want to handle just that one element. However, when I click on another link, the active class is not being removed from the previous ones. Can anyone offer assistance with this issue? Here's my code: let parentT = document.qu ...

Utilizing Angular.JS to implement a template featuring tags

My web application built with AngularJS includes <p> tags. I am looking to apply a template from a server file to the innerHTML of these <p> tags. The template consists of simple text with various tags like <b>, <ol>, and other text ...

Having trouble implementing CORS in a Slim API

I'm facing challenges in setting up CORS with Slim and AngularJS. AngularJS HTTP Request: $http({ method: 'GET', headers: { 'Content-Type': 'application/json', Accepts: 'application/json&ap ...

Transforming JavaScript/Angular 1 from using Promise.all to async-await technique

Within the $onInit() function, I set two web service calls to run concurrently and store their responses in variables named referencesPromise and contactTypesPromise. If necessary, a new method can be created for this purpose. $onInit() { const referenc ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

If the background color is blue, then element class will be added

Currently exploring the realm of JavaScript, I am tackling a challenge with adding a class to an element based on its background color. Specifically, I aim to add a class to elements with a background color set to rgb(32, 44, 62). However, my current imple ...

What methods can I use to adjust my HTML content once I have parsed my JSON file?

<script type="text/javascript"> window.alert = function(){}; var defaultCSS = document.getElementById('bootstrap-css'); function changeCSS(css){ if(css) $('head > link').filter(':first').replaceWit ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

Defining the signature of an unnamed function in TypeScript

Within my Express code, I have an anonymous function set up like this: app.use((err, req, res, next) => { // ... }); I am looking to specify the type of the function as ErrorRequestHandler (not the return type). One way to achieve this is by defining ...

Tips for incorporating an HTML file using ng-include in double curly brace syntax {{ }}

Here is the code snippet I am working with: <div ng-repeat="pTabs in child.productTabs" ng-click="toggleProductTab($index)" ng-if="productTabIsActive(pTabs, $index)"> <div ng-repeat="specs in pTab.additionalSpecs"> <p>{{spec ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...