AngularJS - alternative use for isolated scope expressions ("&")

237 Views Asked by At

I know "&" binding used to pass the method (expressions) to directives isolate scope, so the directive will able to execute it when needed.

Many times I need to "pass" the same expression from my main controller, more than one level deep, to nested directive (2-3 levels). This why on my own, I don't like to use "&" for that purpose. For me, sending "callbacks" using "=" bindings works much better. But this is not a question.

The question is:
What for, I can use "&" in addition to passing functions? Can I have something like this: my-directive-click="clickCount +=1"?

2

There are 2 best solutions below

4
On

In reality, the & is meant as one-way-data-binding.

So = is two-way-data-binding which means changes done on the directive will persist to the original object.

@ is just a string.

And & is special. The thing is that it creates a getter for your value, in the case of an invoked function, the getter actually calls the function. I tend to do this on the DDO:

.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {      
      getParameters: '&?params'
    }

So in this way, the value bound to the scope is getParameters (so it's clear is a getter) but on the directive element you will only refer it as params:

<my-directive params="ctrl.params">

Your question is vague though and even though you may be able to do what you were asking, I think it would be best to do that inside the directive rather than the way you proposed.

I hope this helped.

0
On

& is more about allowing you to deal with expressions, and more importantly (in my eyes) allows you to place parameters into the calling parent's scope.

For instance if you have:

scope: {
    something: '&'
} 

and then in that directives template you could do:

<select ng-model="selection" ng-change="something({$item: selection})" ...>

The caller/user of this directive than can ACCESS $item in the expression passed to something, i.e. $item is placed on its scope.

e.g.

<my-dir something="myOwnVar = $item + 1"></my-dir>

here is a plunker with an example of this, including chaining (multiple nested calls of a & expression): http://plnkr.co/edit/j4FCBIx0FVz4OT0w50bU?p=preview