Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here

Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I am struggling to pinpoint the issue with my approach.

The main problem at the moment appears to be that even though resolve() is being called as expected upon clicking, 'selected' remains undefined.

Here is the HTML structure:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Angular: directive using &amp; - jsFiddle demo</title>     
  <script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  <style type='text/css'>        
  </style>

</head>
<body ng-app="myApp">
  <div grand-parent>
    <span>selected: {{text}}</span>
    <div parent resolve="resolve"></div>
</div>
</body>
</html>

And here is the JavaScript code:

var myApp = angular.module('myApp',[]);

myApp.directive('grandParent', function() {
return {
    scope:{
        resolve: "&"
    },
    link: function($scope, $element) {
        $scope.resolve = function(selected){
            $scope.text = selected
            }
        }
    };
});

myApp.directive('parent', function(){
    return{
        scope: {
            resolve: "&"
        },
        template: "<div child resolve='resolve'></div>"
    };
});

myApp.directive('child', function() {
    return {
        scope: {
            resolve: "&"
        },
        template: "<div>Click me!</div>",
        link: function($scope, $element) {
            $element.on("click", function(){
                $scope.$apply(function(){
                    $scope.resolve({selected: "Yahoo!!"});
                });
            });
        }
    };
});

Answer №1

resolve: "&" represents a mapping concept. Consider the following code:

myApp.directive('grandParent', function() {
return {
    scope:{
        resolve: "&"
    },
    link: function($scope, $element) {
        $scope.resolve = function(selected){
            $scope.text = selected
            }
        }
    };
});

In this case, you are attempting to map "resolve" in a scenario where "grandParent" does not have an attribute named "resolve". This will result in nothing being mapped.

If you wish to share data between directives, consider the following approach:

View

<div data-grand-parent resolve="resolved()">
    <div data-parent  ></div>
</div>

Directives

var app = angular.module('test');

app.directive('grandParent', function() {
    return {
        scope : {
            resolve : "&" 
        },
        controller: function($scope){
            this.getResolve = function(){
                return $scope.resolve;
            };
        }
    };
});

app.directive('parent', function() {
    return { 
        require: "^grandParent", 
        link: function(scope, element, attr, grandParentCtrl){
            grandParentCtrl.getResolve()();
        },
        template : ""
    };
});

Controller

angular.module('desktop')
  .controller('MainCtrl', function ($scope, mocks) {

    $scope.resolved = function(){
        console.log("calling $scope.resolved() ...");
    };

  });

Output

calling $scope.resolved() ...

This setup allows us to define a "resolved" function in our controller and map it to the "resolve" property in the "grandParent" directive. By injecting "grandParent" into other directives, we can access this mapped function.

I would suggest exploring resources like the book "AngularJS" by Brad Green and Shyam Seshadri, as well as tutorials on

ps. Apologies for any language errors ;/

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

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

Is the button failing to direct you to the intended destination?

I'm facing an issue with a button tied to a JavaScript function using onClick(); My interface allows me to ban players on a game server, but when I select anyone here: https://i.stack.imgur.com/kcE1t.png, it always selects wartog for some reason. In ...

The process involves transferring information from a specific div element to a database. This particular div element obtains its data after receiving an appended ID

It's a bit complicated, but I'm working on creating a tag system. I'm fetching data from a database with an AJAX call using the "@" symbol. Everything is working fine - the tags are being generated, but I'm having trouble retrieving and ...

Utilizing tag keys for inserting text and adjusting text sizes within a Web application

Creating an online editing interface for coursework where keyboard events are used. The goal is to have the tab key insert text, while also reducing the size of the text on that line. However, upon using getElementById, an error message pops up stating: ...

Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi. 1) First, I want to check if the field category exists. If it doesn't, I should display the error message category requ ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...

The reference to Angular is missing

My current file setup includes an index.html file and an app.javascript file. I keep encountering an error that says "Angular is not defined," even though my script files appear to be properly placed. Below are the contents of my index file and app.js file ...

BreezeJS model, Knockout integration, empty relationships

I am facing an issue where, when using breeze manager.saveChanges(), only the navigation properties are not sent to the server. The rest of the data is being transferred properly. I am relatively new to Breezejs and hoping someone experienced can assist me ...

What methods can be used to identify the pattern entered by the user for data types such as `Int`, `VarChar`, `

I have a dropdown menu containing data types. There is also a text box for entering Regex patterns. If "/test/" is entered in the textbox or "Int" is selected from the dropdown, then it's an incorrect pattern. If "/[0-9]/" is entered in the ...

When attempting to submit a form using AngularJS in conjunction with Rails, an error arises due to the

After the page loads, I encounter a 404 error because the $resource is returning nil for :city_id. I am new to angularjs so any help in explaining this would be greatly appreciated. I am having trouble making the form entries persist because the same $res ...

Change object values to capital letters

Upon retrieving myObject with JSON.stringify, I am now looking to convert all the values (excluding keys) to uppercase. In TypeScript, what would be the best way to accomplish this? myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", ...

What is the best method for sending the styled and checked option via email?

Just finished customizing the checkboxes on my contact form at cleaners.se/home. Here's my question: If I select "telefon," how can I ensure that this option is sent to my email? In Contact Form 7, I used to simply type a shortcode. Is there a simila ...

The scope's attribute is present, but the variable within the scope's attribute is not

Currently, I am delving into angularJS development, but encountering a perplexing issue. I am attempting to format a JSON into a table with intricate rules. The JSON structure currently is as follows: { "id":"test", "title":"Test Sample", "de ...

What is the best way to access the id attribute of a <td> element within a <tr> using jQuery?

Can someone assist me with this issue? Is there a way to get the ID of the first or second td element instead of using a loop? Here is an example: "<tr class='test_point' id="+fileName+"><td><img src='"+ROOT_PATH+"/assets/d ...

Struggling to construct a binary tree as my descendants are not arranged in the right sequence

I am currently working on building a binary tree using PHP, MySQL, and a jQuery plugin developed by Frank-Mich. Here is the progress I have made so far... DATABASE STRUCTURE CREATE TABLE IF NOT EXISTS `members` ( `id` int(11) NOT NULL AUTO_INCREMENT, ...

I am in need of a blank selection option using an md-select element, and I specifically do not want it to be

I'm currently utilizing Angular Material with md-select and I am in need of creating a blank option that, when selected, results in no value being displayed in the select dropdown. If this blank option is set as required, I would like it to return fal ...

The Battle: AJAX FormData vs encodeURI

When utilizing jQuery's encodeURI(), the data transmitted through AJAX appears in this format: key1=true & key2=34 & ... In order to send an image via AJAX, I employ the FormData() method, resulting in the AJAX data without an image looking ...

jQuery when - anticipate the fulfillment of multiple success/done callbacks

When using $.when to determine when an array of ajax promises are finished, I have noticed that although the ajax calls themselves are completed when $.when fires, their callbacks and done functions are not. How can I make sure to wait for the callbacks to ...

Utilize Django's TemplateView in ModelAdmin's add_view for seamless integration

As per the Django Admin site documentation, I have discovered that I can customize ModelAdmin.add_view to inject a custom view. My intention is to include a TemplateView to modify an admin page for adding or changing models. This unique view will feature ...