简体   繁体   中英

AngularJS - Passing parameters from directive back to the controller

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM