W3docs

AngularJs Directive Scope '&' Method

The “&” operator allows you to invoke or evaluate an expression on the parent scope of whatever the directive is inside of. Learn with W3docs tutorial.

Many AngularJS developers have already known about AngularJS Directives and probably know about directive scope and its methods.

Warning

Since AngularJS is now a deprecated framework, you can use JavaScript modern frameworks like Vuejs, React and Angular, instead.

As you know, there are 3 AngularJS Directive scope methods: '@', '=', '&', but now we are going to talk about only the '&' method. We are going to see how we can implement the '&' method in our applications.

First, you must define the directive with the & binding in the scope object:

example

app.directive('myDirective', function() {
  return {
    scope: {
      anyFunction: '&'
    },
    template: '<button ng-click="anyFunction()">Click me</button>'
  };
});

When you define any function inside the current scope and want to implement it in a directive, remember one thing: you have to pay attention to your function's arguments and their order. For example, if you defined a function like this:

example

$scope.myFunction = function(arg1, arg2) {
  // ...
};

When you use the directive, pass the expression in the HTML:

example

<my-directive any-function="myFunction(arg1, arg2)"></my-directive>

Inside your directive, you have to use a special syntax to send arguments. AngularJS & bindings expect an object that maps the local argument names to the actual values:

example

// Inside your directive's link or controller function
scope.anyFunction({arg1: value1, arg2: value2});

This object-mapping syntax is the standard and only way to pass arguments to a & binding. You do not pass the object literal in the HTML attribute.

Here is a practical example. Let's say you have a list of items, and for every item, you have a delete action, but you want a confirmation modal. You can create a directive with its template (the modal) and send your delete function into it. Inside your directive, you can trigger the modal on an event. When the user confirms, you call the bound function with the specific item argument:

example

// Inside directive controller/link
function confirmDelete() {
  // After user clicks "Yes" in modal
  scope.anyFunction({item: selectedItem});
}

This approach allows you to use a single directive function to handle different items without needing separate functions for each delete action.