Reputation: 397
I'm a new-be to Javascript and AnuglarJS but I have some Java experience. I'm studying AngularJS developer's guide on directive and have a question.
In the section "Creating a Directive that Wraps Other Elements" there is a example/demo. In the example/demo:
The template of the directive myDialog is as bellow:
<div class="alert">
<a href class="close" ng-click="close({message: 'closing for now'})">×</a>
<div ng-transclude></div>
</div>
I cannot understand close({message: 'closing for now'})
here. From the directive's definition:
scope: {
'close': '&onClose'
}
So close
is a reference to onClose
in the directive's parent. onClose
is not defined in the controller but appears in it's template as an attribute and further refer to hideDialog(message)
:
<div ng-controller="Controller">
{{message}}
<my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)">
Check out the contents, {{name}}!
</my-dialog>
</div>
Questions:
onClose
is not specifically defined in the controller, how can it take and process any input parameter passed from the directive?hideDialog
in the controller takes a string parameter, but close
in the directive passes an object {message: 'closing for now'}
to onClose
. how onClose
does the magic of extracting the value from the message
key of the input and passing it to the target function hideDialog
?Upvotes: 0
Views: 355
Reputation: 5432
Angular Directives have multiple ways of defining values that can then be bound to the directive's controller. The '&' is how you pass a function from a parent controller to the directive controller. In the instance defined above, the parent controller (Controller) has a method (hideDialog) on it's 'scope' (not cool really) that takes a single argument (message). The '&onClose' is bound to the directive controller's 'close' variable. When 'close' is called, it needs to pass 'message' as if it were a named argument (es6 sorta fashion here). This is because of the way the directive controller's variable extends the parent controller's methods under-the-hood, and how it needs to pass variables to that method.
Upvotes: 1