Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive binding a function with multiple arguments

I'm having some trouble binding a function defined in a controller with a callback function in a directive. My code looks like the following:

In my controller:

$scope.handleDrop = function ( elementId, file ) {     console.log( 'handleDrop called' ); } 

Then my directive:

.directive( 'myDirective', function () {     return {       scope: {         onDrop: '&'       },       link: function(scope, elem, attrs) {         var myFile, elemId = [...]          scope.onDrop(elemId, myFile);       }     } ); 

And in my html page:

<my-directive on-drop="handleDrop"></my-directive> 

Having no luck with the code above. From what I've read in various tutorials I understand I'm supposed to specify the arguments in the HTML page?

like image 884
Joseph Paterson Avatar asked Sep 24 '13 05:09

Joseph Paterson


1 Answers

Alternative method that will survive minification

Leave your html as it was:

<my-directive on-drop="handleDrop"></my-directive> 

Change the call to:

scope.onDrop()('123','125') 

Notice the extra opening and closing parenthesis given to onDrop. This will instantiate the function instead of injecting the function's code.

Why is it better

  1. Changing the parameters' names in the handleDrop() definition (or even adding some more, if you handle it correctly) will not make you change each of the directives injections in the html. much DRYer.

  2. As @TrueWill suggested, I'm almost sure the other solutions will not survive minification, while this way code stays with maximum flexibility and is name agnostic.

Another personal reason is the object syntax, which makes me write much more code:

functionName({xName: x, yName: y}) // (and adding the function signature in every directive call) 

As opposed to

functionName()(x,y) // (zero maintenance to your html) 

I found this great solution here.

like image 200
Nuriel Avatar answered Oct 02 '22 12:10

Nuriel