I think I understand what you're trying to accomplish, so I'll give an example.
You have a controller (myController
) that calls a directive (myDirective
) that calls another directive (anotherDirective
), and you want to pass a "callback" function from myController
through myDirective
down to anotherDirective
. Here is how you can do it:
angular
.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.foo = function(param) {
alert('This function is declared on the main controller but called from a directive a few levels deep. Parameter: ' + param);
};
}])
.directive('myDirective', function() {
return {
template: `
<h1>My Directive</h1>
<another-directive callback="myFunction(b)"></another-directive>
`,
scope: {
myFunction: '&'
}
}
})
.directive('anotherDirective', function() {
return {
template: `
<h2>Another Directive</h2>
<button data-ng-click="callback({b: {a: 'hello world'}})">Click Me</button>
`,
scope: {
callback: '&'
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<my-directive my-function="foo(a)"></my-directive>
<div>
The key to this starts in the lowest level directive anotherDirective
:
<button data-ng-click="callback({b: {a: 'hello world'}})">Click Me</button>
Now remember how callback
was set on its parent:
<another-directive callback="myFunction(b)"></another-directive>
And how myFunction
was initially declared on its parent:
<my-directive my-function="foo(a)"></my-directive>
I'm struggling to think of a way to explain it properly, but with this example you should be able to see the pattern with how the expressions bubble up to each parent.