cezarlamann
cezarlamann

Reputation: 1533

AngularJS and FancyTree: Events firing, but with undefined parameters

I'm trying to write a directive for fancytree. The source is loaded through ajax and almost everything looks like a charm. The tree is correctly shown, events are firing nice, but the parameters get undefined at the controller side.

It looks strange, because when I set a function(event, data){ ... } for the events (like activate or beforeSelect as seen in the docs) both event and data are nicely set.

Where I'm doing it wrong?

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
  };

Upvotes: 1

Views: 520

Answers (1)

PSL
PSL

Reputation: 123739

You are missing one important piece in the function binding of directive. They need to be passed in as object with property name same as that of the argument names. i.e

scope.activateFn(event, data);

should be

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

Or in otherwords, the properties of the object passed in through the bound function ({event: e,data: d}) needs to be specified as argument of the function being bound (genericEvt(event, data)) at the consumer side.

Though the syntax can be confusing at the beginning, you can as well use = binding instead of & though & is to be used specifically for function binding. Ex:

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

and

 activate-fn="genericEvt"

Upvotes: 2

Related Questions