Ways to transfer information from a directive to a controller

In my application, I have created a custom directive that utilizes D3.js. The goal is to trigger an API call to fetch more data when a user clicks on a node within the D3 visualization. This involves accessing the data linked to the clicked node and sending it back to the controller. The controller then manages the process of fetching additional data.

My current focus is on logging the data of the clicked node in my controller. However, I am encountering an issue where this data is showing as undefined in the controller.

Here is the relevant code snippet from the directive:

angular.module('gameApp')
    .directive('gmLinkAnalysis', gmLinkAnalysis);

  gmLinkAnalysis.$inject = ['$location', 'd3'];

  function gmLinkAnalysis($location, d3) {

    var directive = {
      restrict: 'E',
      templateUrl: '/app/gmDataVis/gmLinkAnalysis/gmLinkAnalysis.directive.html',
      scope: {
        data: '=',
        logNode: '&'
      },
      link: function(scope) {

        ...

        function click(d) {
          scope.logNode(d);
        }
      }
    };
    return directive;
  }
  

HTML:

<gm-link-analysis data="connections.users" log-node="connections.logNode(d)"></gm-link-analysis>
  

Below is the relevant section from the controller code:

angular.module('gameApp')
    .controller('ConnectionsController', ConnectionsController);

  function ConnectionsController() {
    var vm = this;

    ...

    vm.logNode = function(d) {
      console.log(d);
    };
  }
  

When I replace d in the HTML with a string like "hello world" (

log-node="connections.logNode('hello world')"
), it logs correctly. Therefore, the issue seems to be related to passing the data correctly as a parameter in the HTML. How can I resolve this problem?

Answer №1

To ensure accuracy, make sure to include the parameter in the function call:

Therefore, within your directive, it needs to be:

function select(item) {
  scope.updateSelection({item: item})
}

For reference, here is a demonstration: http://jsfiddle.net/lightlynx/3dhs62j/

Answer №2

When working with directives, you have the option to pass a model with attached methods. However, I find that utilizing the $.broadcast service is a cleaner approach for maintaining my codebase.

Here's an example:

function click(d) {
   $rootScope.$broadcast('someEvent', d);
 }

Within the controller:

angular.module('gameApp')
   .controller('ConnectionsController', ConnectionsController);

 function ConnectionsController() {
   var vm = this;

   vm.$on('someEvent', function(event, data) {
     console.log(data)
   });
 }

If you prefer passing methods to the directive, you can refer to this simple example for guidance.

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

The Javascript Node class encountered an error: X has not been defined

I have a class that looks like this: const MongoClient = require("mongodb").MongoClient; const ConnectionDetails = require("./ConnectionDetails").ConnectionDetails; const Recipe = require("./recipe").Recipe; var ObjectId = req ...

Transmit the identifier of the span tag to the URL seamlessly without the need to refresh

<div id="unique50">Greetings</div> Transfer the code 50 to the designated link by clicking on the specific div element without requiring a page reload ...

What makes CVE-2021-33623 susceptible to ReDoS attacks?

CVE-2021-33623 points out that the code snippet below (addressed in this commit, along with test cases) is susceptible to ReDoS vulnerabilities: trimNewlines.end = string => string.replace(/[\r\n]+$/, ''); What makes it prone to ReD ...

Running a Node.js script on an Express.js server using an HTML button

I've got an HTML button: <button id="save" type="button" onclick="save()">Save</button> and in my JavaScript code, I want it to execute something on the server side using node.js Here's what I have in mind: function save() { / ...

Unexpected background image slideshow appearance

I am encountering an issue with my slideshow where the last image briefly appears before the first image loads in a continuous loop. The offset of the initial image causes it to start at the middle of the window, and in Google Chrome and Safari, subsequent ...

Is the variable not being initialized outside of the function?

I'm really struggling with this async issue. I can't seem to get it to work because the summonerData array is not being set. I have a feeling it has something to do with async, but I'm not sure how to troubleshoot it. var summonerName = req ...

Steps to quickly display the Badge after switching routes on the page

This is my initial post, so please bear with me if I haven't provided enough details or if I've made a foolish mistake For my semester project, I am constructing a shop using basic ReactJS (without Redux or any database). Just to clarify, I have ...

Combining arrays based on a key in Node.js

I have the following two objects that need to be merged: [ { "response_code": 1, "response_message": [{ "a": 1000, "b": 1000001, "c": 10000002 }] }] [ { "response_code": 1, ...

What are the steps to set up Twitter Bootstrap without using offset blocks?

I am currently setting variable values using AngularJS. <div class="col-md-5">Cost:</div> <div class="col-md-7">{{ cost }}</div> <div class="col-md-5">Total:</div> <div class="col-md-7">{{ total }}</div> Af ...

Searching for a pattern and replacing it with a specific value using JavaScript

I need to find all occurrences of an unknown string within a larger string that is enclosed in brackets. For example, the string may look like: '[bla] asf bla qwr bla' where bla is the unknown string I need to locate. Is it possible to achieve th ...

Show a nested array retrieved from JSON in a React component

I need assistance in displaying data from my JSON file, particularly an innested array using map(). The field I want to display as a list is analyzedInstructions, which looks like this: How to prep (from p How to prep /p) Steps: Remove the cauliflower&a ...

What is the best way to pass ng-model value from directive to controller in Angular?

I recently developed a custom directive which includes a text box. I am facing difficulties in retrieving the value of the model associated with it in my controller. Despite my efforts, I have not been successful. Below is the code for my directive: app. ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Navigating an array to link values to anchor tags

I'm struggling with an array that contains image file names ["1352.jpg", "1353.jpg", "1354"]. My goal is to loop through this array and generate anchor links for each item separated by commas. I've attempted the following code snippet, but it&apo ...

Managing browser closure (x) using JavaScript or jQuery

Is there a way to handle browser close (by clicking the cross on the top right side) using javascript or Jquery without triggering events whenever the page is refreshed, navigated back and forth in the browser? I have seen many forums and blogs suggesting ...

I created some jQuery code that modifies a button when it is hovered over, however, I ended up writing the code individually for each button. What steps can I take to turn it

Is there a way to turn the code for each button on my website into a jQuery function that can be applied to any button? This is how the code currently appears: $(document).ready(function() { $("#linkXML").hover( function() { ...

What is the technique for accessing the original function within a class using a proxy?

I attempted to monkey patch a function within my class using Proxy. Is there a way to access and execute the original function? class foo { x = 10; bar() { console.log({ x: this.x }); } } foo.prototype.bar = new Proxy(foo.prototype.bar, { ap ...

What could be causing issues with my jQuery POST call?

I am attempting to establish authentication with a remote service using jQuery. Initially, I confirmed that I can accomplish this outside of the browser: curl -X POST -H "Content-Type: application/json" -H "Accept: appliction/json" -d '{"username":" ...

Tips for organizing multiple TextField components within a Grid container using Material-UI

I utilize Material-UI for my front-end design needs. I have a query related to the Grid layout feature. My goal is to include 7 TextField elements, but they are appearing overlapped. When I modify all 7 TextField elements from xs={1} to xs={2}, they become ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...