angularjs directive call function specified in attribute and pass an argument to it

angularjs-directive

Solution

Marko's solution works well.

To contrast with recommended Angular way (as shown by treeface's plunkr) is to use a callback expression which does not require defining the expressionHandler. In marko's example change:

In template

<div my-method="theMethodToBeCalled(myParam)"></div>

In directive link function

$(element).click(function( e, rowid ) {
  scope.method({myParam: id});
});

This does have one disadvantage compared to marko's solution - on first load theMethodToBeCalled function will be invoked with myParam === undefined.

A working exampe can be found at @treeface Plunker

Problem

I want to create a directive that links to an attribute. The attribute specifies the function that should be called on the scope. But I also want to pass an argument to the function that is determined inside the link function. ``` <div my-method='theMethodToBeCalled'></div> ``` In the link function I bind to a jQuery event, which passes an argument I need to pass to the function: ``` app.directive("myMethod",function($parse) { restrict:'A', link:function(scope,element,attrs) { var expressionHandler = $parse(attrs.myMethod); $(element).on('theEvent',function( e, rowid ) { id = // some function called to determine id based on rowid scope.$apply(function() {expressionHandler(id);}); } } } app.controller("myController",function($scope) { $scope.theMethodToBeCalled = function(id) { alert(id); }; } ``` Without passing the id I can get it working, but as soon as I try to pass an argument, the function is not called anymore

Original source