How to pass custom functions to AngularJS directives

In case you need to pass a callback to your AngularJS directives, looks like one way is to create an isolated scope and create a member with the ‘&’ attr. Here’s a quick&dirty example:

myApp.directive('callbackDirective', function () {
return {
scope: {
callback: '&'
},
restrict: 'E',
templateUrl: 'my-template.html'
controller: ['$scope', function ($scope) {
$scope.foo = function () {
if ($scope.callback) {
$scope.callback();
}
};
}]
}
})

view raw
directive.js
hosted with ❤ by GitHub

<callback-directive callback="myCallback()" />

view raw
page.html
hosted with ❤ by GitHub

In case you have to pass some arguments to the callback, here’s how:

myApp.directive('callbackDirective', function () {
return {
scope: {
callback: '&'
},
restrict: 'E',
templateUrl: 'my-template.html'
controller: ['$scope', function ($scope) {
$scope.foo = function (bar) {
if ($scope.callback) {
$scope.callback({value: bar});
}
};
}]
}
})

view raw
directive.js
hosted with ❤ by GitHub

<callback-directive callback="myCallback(value)" />

view raw
page.html
hosted with ❤ by GitHub

Notice that the argument is transformed in a javascript object and passed to the callback which is actually a wrapped function around the one you passed.

How to pass custom functions to AngularJS directives
Scroll to top