0

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'})">&times;</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:

  1. Since onClose is not specifically defined in the controller, how can it take and process any input parameter passed from the directive?
  2. 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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.