AngularJs Directive Scope '&' Method

Many AngularJs developers have already know about AngularJs Directives and probably know about directive scope and it's methods.

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 '&' method.We are going to see, how we can implement method '&' in our applications.

When we define any function inside current scope and want to implement it to any directives,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:

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

You have to remember your functions argument and their order: 1:arg1,2:arg2 ...

When you defined any directive and want to implement myFunction into it,lets see how you can do it.

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

When you chose to use that syntax,inside your directive (where you want to use it) you have to use special syntax to send arguments.

Here is the syntax.

// inside you directive
scope.anyFunction({arg1: [value], arg2: [value], arg3: [value], ...})
// Or
scope.anyFunction({newArgName1: [value], newArgName1: [value], newArgName1: [value], ...})

But Angular will not be so cool if there wasn't the following second syntax of '&' method. This way is very useful when you don't want to have compile or link function of your directive. Or you don't want to have a bunch of codes.

Here is the second way.

<my-directive any-function="myFunction({arg1: [value], arg2: [value], arg3: [value], ...})"></my-directive>
<my-directive any-function="myFunction({newArgName1: [value], newArgName1: [value], newArgName1: [value], ...})"></my-directive>

And inside your directive you can only call anyFunction() (with no any arguments).

Here is a simple example, where we can use this way.

Let's say you have a list of items, and for every item, you have to delete action, but you want a confirmation for every delete (for example modal with an answer "yes" or "no"). You can create a directive with it's a template (modal) and send your delete function into it. Inside your directive, you can only make an event for opening modal. On "yes" will be your confirm function. Of course, every delete action can have a different argument. But what to do? How we can use ng-click with different function?

The answer is: you needn't use different function. You can use only one function to call it without any argument like the top example.