AngularJS and FancyTree: Surprising Triggering of Events with Undefined Parameters

I have been working on a directive for fancytree that loads its source through ajax. Everything seems to be functioning correctly - the tree displays as expected, events are triggering properly, but the parameters end up being undefined in the controller.

It's puzzling because when I define a function(event, data){ ... } for events (such as activate or beforeSelect as outlined in the documentation), both event and data are set correctly.

What am I missing here?

Thank you in advance!

Directive

angular.module('MyAppModule', [])
.provider('MyAppModuleConfig', function () {
    this.$get = function () {
        return this;
    };
})
.directive('fancytree', function () {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: {
            activateFn: '&',
            //long list of events, all stated with "<sth>Fn : '&'"
            selectFn: '&',
            selectedNode: '=',
            treeviewSource: '=',
            enabledExtensions: '=',
            filterOptions: '='
        },
        template: '<div id="treeview-container"></div>',
        link: function (scope, element) {
            element.fancytree({
                source: scope.treeviewSource,
                activate: function (event, data) {
                    console.log(event, data); // ok, parameters are all set
                    scope.activateFn(event, data); 
                    // function fires right, but all parameters 
                    // are logged as undefined
                }
            });
        }
    };
});

HTML

    <fancytree ng-if="tvSource" treeview-source="tvSource" 
        activate-fn="genericEvt(event, data)"/>

Controller

  TreeViewSvc.query()
      .success(function (response) {
          $timeout(function ()
          {
              $scope.tvSource = response;
          });
      });
  $scope.genericEvt = function (event, data) {
      console.log('event', event);
      console.log('data', data);
      // function is firing, but all parameters come undefined
  };

Answer №1

When binding functions in a directive, it is crucial to pass them in as an object with property names matching the argument names.

scope.activateFn(event, data);

should be written as:

scope.activateFn({event: event, data: data});

In simpler terms, the properties within the object passed through the bound function ({event: e, data: d}) must align with the arguments of the function being bound (genericEvt(event, data)) on the consumer side.

Although the syntax may seem confusing initially, you have the option to use = binding instead of &, which is specifically designed for function binding. For example:

 ....
 activateFn: '=',
 ....

and

 activate-fn="genericEvt"

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 I make a clickable button or link within an anchor tag that is still able to be right-clicked?

Hey there, I'm currently working on a notification dropdown menu where each <li> contains a link or an <a> tag. I'm aiming to create something similar to Facebook's notification system. However, the challenge lies in trying to ...

Steps for deploying an ejs website with winscp

I have developed a Node.js web application using ExpressJS, with the main file being app.js. Now I need to publish this website on a domain using WinSCP. However, WinSCP requires an index.html file as the starting point for publishing the site. Is there ...

What is the most efficient method to refresh $scope following data retrieval from a service in AngularJS?

In my current project using angularJS, I have encountered a challenge while working with an API service to fetch and display data in different parts of the app under various controllers. Initially, everything ran smoothly until I centralized the API calls ...

Meteor does not come with build packages included

I am currently working on creating native versions of a small meteor application that I developed. Running them on iOS or Android using the meteor run command is successful, and using meteor build with --debug generates an ipa/apk that functions properly. ...

Exploring the world of AngularJS, repeating fields and handling special characters

I am looking to showcase the batters and their statistics from a JSON file for my team in a table using AngularJS. HTML: <table class="table" ng-controller="players"> <tr ng-repeat="x in player | orderBy:orderByField:reverseSort"> ...

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...

Continuous Playback of Sound

Is there a way to autoplay an audio in loop without being blocked by browsers? Code : <audio id="audio1" src="assest/sound/1.mp3" autoplay="" /> <script> a = document.getElementById('audio1&apo ...

Dealing with a passed EJS variable in string form

When working with passed data in ejs, I usually handle it like this and it works perfectly: let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>'); However, I encountered a problem when trying to dynamically pass a string variabl ...

What is the best way to generate dynamic clickable keywords that trigger a modal dialog in AngularJS using uibModal?

As a beginner in AngularJS, I am working on a site that presents a list with each element being delivered from the server as a string. Within these elements, I use bars as delimiters for keywords that I want users to be able to click on (e.g., this is a |k ...

Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving ...

Incorporating React into an already existing webpage and accessing URL parameters within a .js file

Following the official guidelines: To include React in a website, visit https://reactjs.org/docs/add-react-to-a-website.html I have created a file named test.html with the following content: <!DOCTYPE html> <html> <head> < ...

Passing ng-model data from a directive component to a controller in AngularJS

My inspiration from angular ui has led me to create a front-end library made up of components, all as angularjs directives. This allows users to easily implement directives with specific configurations and achieve the desired component results. Here is an ...

How can I empty the value of a UI widget (such as an input field, select menu, or date picker) in Webix UI?

Is there a way in Webix UI to clear widget values individually, rather than collectively based on form id? I'm looking for a method using a mixin like $$(<form-id>).clear(). I need control of individual elements, so is there a proper way to res ...

"Implementing a feature in Django that clears the input field upon clicking the clear button

I am working on a Django HTML file that includes an input field and a clear button. I need to clear the input field when the clear button is pressed. Is it necessary to use JavaScript for this task, or is there another way to achieve it? <form> ...

Trigger an alert box using JavaScript after a successful submission

PHP Script Explanation The following PHP script is executed once the corresponding form has been filled out: <?php $connect = mysql_connect($h, $u, $p) or die ("Connection Failed."); mysql_select_db($db); ## Prevent SQL Inje ...

Incorporating Physics into OBJ Model with ThreeJS

Currently experimenting with PhysiJS in conjunction with ThreeJS. Recently exported an OBJ model from Blender, only to find that when loaded with OBJLoader, it appears as a BufferGeometry. The issue is that it lacks a crucial vertices property required by ...

Limit access to all pages, with the exception of the home page, in Django

During the development of my Django application, I organized the functionality into sub-functions and implemented them in individual apps. To display results on the homepage instead of redirecting to a sub-function app page, I utilized ajax and JavaScript. ...

Issue with Material-UI tab when using a datatable within it's content

I implemented the Simple Tabs feature from Material-UI with a Tab containing a Datatable using React-Data_Table. However, I noticed that this particular tab is not responsive like the others when the table is full. Empty Full Here's a snippet of th ...

What is the process to retrieve the username from my system and display it in a web browser?

Seeking assistance to retrieve my system's username and display it on a web browser. Currently, I have been using ActiveXObject method, which successfully retrieves the username, but has drawbacks such as requiring ActiveX to be enabled and only works ...

Attempting to retrieve an object's attribute

Hey! I have a question regarding the screenshot in this link: I'm trying to access the user object with the property team. So far, I've attempted using data.Object, but it returns an undefined output. I also tried using data.user but that resul ...