AngularJS 调用父子指令控制器函数

AngularJS calling from Parent to Child Directive controller function

我习惯在 Angular 工作,现在我在 AngularJS(反过来)

我有一个指令:

<li  ng-mouseover="vm.setCurrentEditedTile(item.id)">
   <panel-buttons-directive ></panel-buttons-directive>
</li>

我的面板按钮指令有一个名为 ButtonsController 的控制器。 当用户将鼠标悬停在 <li> 元素之上时,我想要什么,它 运行 是子控制器内部的一个函数。这样我就有了一个单独的 "Module",其中指令中有按钮 HTML,控制器中有函数,我可以从父级调用该函数。

Link: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md

一种方法是让指令在初始化时发布 API:

<fieldset ng-mouseover="pbdAPI.setCurrentEditedTile(item.id)">
  Mouseover Me
</fieldset>

<panel-buttons-directive on-init="pbdAPI=$API">
</panel-buttons-directive>
app.directive("panelButtonsDirective", function() {
  return {
    scope: { onInit: '&' },
    bindToController: true,
    controller: ButtonsController,
    controllerAs: '$ctrl',
    template: `<h3>Panel Buttons Component</h3>
               <p>Current edited tile = {{$ctrl.id}}</p>
               `,
  };
  function ButtonsController() {
    var $ctrl = this;
    var API = { setCurrentEditedTile: setCurrentEditedTile };
    this.$onInit = function() {
      this.onInit({$API: API});
    };
    function setCurrentEditedTile(id) {
      $ctrl.id = id;
    }
  }
})

上例中的指令使用表达式 & 绑定在初始化时发布其 API。

The DEMO

angular.module("app",[])
.directive("panelButtonsDirective", function() {
  return {
    scope: { onInit: '&' },
    bindToController: true,
    controller: ButtonsController,
    controllerAs: '$ctrl',
    template: `<h3>Panel Buttons Component</h3>
               <p>Current edited tile = {{$ctrl.id}}</p>
               `,
  };
  function ButtonsController() {
    var $ctrl = this;
    var API = { setCurrentEditedTile: setCurrentEditedTile };
    this.$onInit = function() {
      this.onInit({$API: API});
    };
    function setCurrentEditedTile(id) {
      $ctrl.id = id;
    }
  }
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h3>Mouseover Component DEMO</h3>
    <p><input ng-model="item.id" ng-init="item.id='tile0'"/></p>
    <fieldset ng-mouseover="pbdAPI.setCurrentEditedTile(item.id)">
      Mouseover Me
    </fieldset>
    <panel-buttons-directive on-init="pbdAPI=$API">
    </panel-buttons-directive>
  </body>