Question

I am creating custom directive where I need to assign function inside object which will be used while passing to my directive. However if I pass method by writing directly name of the function inside template, its working fine. But If I assign that method reference to one of my object properties and then I am using that in my template to passing it to directive but that is not working.

You can see here - jsfiddle

You can see in console. Click on Save button, it will call save function inside directive but from there I am calling controller method which is not working. But if you write function name blabla instead dynamicMethods.myMethod then it will call but in that I got undefined inside alert.

Thank you.

Was it helpful?

Solution

You had it almost right.

First mistake was when you defined dynamicMethods object you're referencing $scope.blabla which didn't yet exist.

Second mistake was when you're passing values to the accept function call which you've bound to parent scope, you need to pass it as:

$scope.accept({msg: "from dir"})

where msg is a local variable named that can be used in the expression value of accept attribute on your custom directive call <editkeyvalue accept="dynamicMethods.myMethod(msg)" ...

I've updated your fiddle accordingly.

When you write accept: "&" you're telling angular to

  1. use $parse service to parse expression (dynamicMethods.myMethod(msg))
  2. "bind" (through javascript closure) $scope of the function returned from step 1 to the original scope (controller's scope in your case)
  3. store the function inside accept property of your directive local scope.

Now if you inspect content's of $scope.accept just before you call it in directive you'll something similar to:

function (locals) {
  return parentGet(parentScope, locals);
}

where locals is an object with local variables used when the we reach evaluation of function returned from $parse. Since there are no named parameters in javascript and we wan't to somehow point that the value local variable msg is "from dir" we're passing it as a simple object where key indicates variable name {msg: "from dir"}.

Angular will look at the expression (a string) to evaluate and find that msg is inside brackets thus it looks like a parameter, which value can be find in locals object.

When the time comes to call the actual function angular will convert locals object to regular array - preserving order of parameters it read from the expression and call the function in a way similar to:

var locals = {msg: "from dir"};
var targetFn = dynamicMethods.myMethod;
var context = dynamicMethods;
targetFn.apply(context, ["from dir"]);

Hope that helps a bit in understanding what is going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top