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 “&”.
Let’s first lay out our directive definition:
In this directive, our controller will have three things bound to it,
vm.functionBind because our directive’s scope definition looks like this:
‘@’: 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
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.