I have a problem passing a function as attribute to a directive, which implements itself recursivly (tree).
I reduced the code to make it easier to understand:
Controller:
vm.addNode = addNode;
vm.editNode = editNode;
vm.deleteNode = deleteNode;
function addNode(node) {
}
function editNode(node) {
}
function deleteNode(node) {
}
HTML:
<tree on-add="vm.addNode(node)"
on-edit="vm.editNode(node)"
on-delete="vm.deleteNode(node)"></tree>
So. If I don't delcare a function, for example on-add like:
<tree on-edit="vm.addNode(node)"
on-delete="vm.editNode(node)"></tree>
the directive-attribute 'onAdd' will be undefined. This happens only at the first call of the directive. If the directive passes itself the on-add function (which should be undefined), the onAdd-attribute in the 'child-directives' is defined (function). Directive:
(function () {
'use strict';
angular
.module('app')
.directive('tree', Tree);
function Tree() {
return {
restrict: 'E',
templateUrl: 'tree.html',
controller: TreeController,
controllerAs: 'vm',
bindToController: true,
scope: {
'onAdd': '&?',
'onEdit': '&?',
'onDelete': '&?'
}
};
function TreeController() {
var vm = this;
console.log(vm.onAdd); // Is undefined on first call (because of &? -> that's good)
// PROBLEM HERE: called recursiv, it will be a function again
}
}
})();
Directive-HTML:
<tree on-add="vm.onAdd({'node': node})"
on-edit="vm.onEdit({'node': node})"
on-delete="vm.onDelete({'node': node})"></tree>
// UPDATE:
I know why, because in the directive, I declare the on-add attribute. Angular wraps the vm.onAdd (which should be undefined) in a function. So the child-directive has onAdd as function and not as undefined.
Someone has a solution to pass it as undefined to each child-directive??
// UPDATE 2:
I made a workaround, doing a link-function and passing a dummy function in it, if any attribute (on-add, on-edit, on-delete) is not set. So I can fire the function without checking it.