Nick Nick - 5 months ago 18
AngularJS Question

angularjs directive - functions not working properly

I'm trying to write a directive that creates a sub menu.

My idea was to make this directive quite flexible, so that I can re-use it if and when needed.

The basic concept is the following:

<my-submenu>
<li my-function="test()">Test</li>
<li my-function="test2()">Test 2</li>
<li my-function="test3(id, type)">Test 3</li>
<li ui-sref="test ({id: id})">Test 4</li>
</my-submenu>


This is quite a simple template. All the elements that needs to be included into my submenu are inside the directive declaration, like above.

The directive part:

angular.module('submenu', []).directive('mySubmenu', [
function() {
var linkFunction;

linkFunction = function(scope, el, attr) {
console.log("scope: ", scope);
console.log("el: ", el);
return console.log("Attr: ", attr);
};

return {
restrict: 'E',
transclude: true,
templateUrl: './submenu.tpl.html',
scope: {
myFunction: '&'
},
link: linkFunction
};
}
]);


and the directive template:

<ul ng-transclude></ul>


Now, the compiled result is pretty much like I want it to be:

<my-submenu>
<ul ng-transclude="">
<li my-function="test()">Test</li>
<li my-function="test2()">Test 2</li>
<li my-function="test3(id, type)">Test 3</li>
<li ui-sref="test ({id: id})">Test 4</li>
</ul>
</hg-room-submenu>


But doing this I lost all of my functions, they are not working anymore.

I read that if you want to use functions, you need to use "&" like i'm doing, but it still not working.

Any suggestion? and also, is this the best approach for creating something like this, or I should do something differently?

Thanks

PS: I also tried to change
my-function
to
ng-click
in the compiled code, but still nothing.

This is actually another thing I need some help with - How can I convert
my-function
to
ng-click
in the compiled directive template? or can I just use
ng-click
instead of
my-function
?

Answer

Using my-function on a nested element inside the directive won't matter for the directive. It will just remain what it is - a meaningless attribute. The & attribute binding (and for that matter - any directive bindings) only work if it's on the same element as the directive.

In your case, you can simply use ng-click in your pre-compiled HTML.

As a side note, changing attributes dynamically after the directives are compiled will not have any effect on the directive or scope bindings - as far as angular's directive compiler is concerned. New attributes will not be compiled into directives or create bindings to the scope and deleted attributes will not "undo" bindings to the scope. The directive compiler will only collect the attributes that exist on the element at the time the element is compiled.