When creating an AngularJS directive, most of the time we want to pass some sort of data to that directive where it is implemented. Of course, Angular gives us multiple ways to do so. Let’s try to make sense of the different binding types: “@”, “=”, and “&”.
(Related: AngularJS Directive’s ‘Restrict’ Real World Guide)
Let’s first lay out our directive definition:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function DemoDirective(){ | |
return { | |
restrict: 'E', | |
scope: { | |
stringBind: '@', | |
objectBind: '=', | |
functionBind: '&' | |
}, | |
template: [ | |
'<p>Hello, {{vm.stringBind}}! Please order donuts:</p>', | |
'<p>Quantity: <input ng-model="vm.objectBind"></p>', | |
'<p><button ng-click="vm.functionBind()">Order Donuts!</button>' | |
].join(''), | |
controller: 'DemoDirectiveController', | |
controllerAs: 'vm', | |
bindToController: true | |
}; | |
} |
In this directive, our controller will have three things bound to it, vm.stringBind
, vm.objectBind
, and vm.functionBind
because our directive’s scope definition looks like this:
stringBind: '@',
objectBind: '=',
functionBind: '&'
‘@’: The first binding is stringBind
and allows us to pass a string to our directive. This binding in one way, it only flows from parent to directive. But, it can be updated multiple times (don’t confuse this with one-time binding).
‘=’: The next binding is objectBind
and it allows us to point to the same object from the parent to the directive. In addition to parent changes being passed to the directive, whenever this object is changed on the directive, the parent will receive the update as well since they are both referencing the same object.
‘&’: The final binding type is functionBind
. This allows us to call parent functions directly from the directive. This way, if you need the directive to trigger a function on the parent, you can just call vm.functionBind()
.
I’ve created a live example of a directive that uses all of these types. In the example, you’ll find we pass the user’s name as a string binding (since that won’t change from the directive). We also pass an object binding to the donuts ordered amount object. This object will be what our directive modifies after the user places their order. Finally, we’ll bind our order function to let the parent know that our donuts were ordered.
JSBin Directive Example: Donut Order
Hope this helps! Feel free to reach out on Twitter (@AdamWeeks) or hang out on Angular Buddies slack group!