【问题标题】:AngularJS calling from Parent to Child Directive controller functionAngularJS 从父调用到子指令控制器函数
【发布时间】:2018-01-03 03:41:06
【问题描述】:

我习惯于在 Angular 中工作,现在我在 AngularJS 上(反之亦然)

我有一个指令:

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

我的面板按钮指令有一个名为 ButtonsController 的控制器。 当用户悬停在&lt;li&gt; 元素上时,我想要什么,它运行一个位于子控制器内部的函数。这样我就有了一个单独的“模块”,其中在指令中有按钮 HTML,在控制器中有函数,并且可以从父级调用该函数。

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

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    一种方法是让指令在初始化时发布 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;
        }
      }
    })
    

    上例中的指令在初始化时使用表达式&amp;绑定来发布其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>

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      • 2015-07-29
      • 1970-01-01
      相关资源
      最近更新 更多