javascript - 从它的父[angularJS]触发子指令中的函数

标签 javascript angularjs angularjs-directive

因此,当在子指令中使用指令属性 require: '^ParentCtrl' 时,我总是完全相反地执行此操作。然后使用 require 调用父函数;但是,我需要反过来做。

问题:
如何从父指令触发子指令中函数的执行。

注意: 1. 子指令在 link: 中没有任何功能 2. 本质上我想要一个反向需求。

父指令:

'use strict';
angular.module('carouselApp')
  .directive('waCarousel', function() {
    return {
        templateUrl: 'views/carousel/wa.carousel.html',
        controller: function($scope) {
            var self = this;
            // this function is being called based on how many pages there are
            self.carouselElLoaded = function(result) {
                var count = 1;
                Carousel.params.pageRenderedLength += count;
                //when all the pages are loaded
                if (Carousel.params.pageRenderedLength === Carousel.params.pageLength) {
                    Carousel.params.carouselReady = true;
                    // !!!!!!!! Trigger will go here!!!!!!!!!//
                    ChildCtrl.drawHotspots(); // (**for placement only**)
                } else {
                    Carousel.params.carouselReady = false;
                }

            };
        }
    }
})

子指令:

'use strict';
angular.module('carouselApp')
  .directive('waHotspots', function() {
    return {
        require: '^waCarousel',
        link: function (scope, element, attrs, ctrl) {
              //call this directive based on how
              scope.drawHotspots = function () {...};
        }
    })

最佳答案

这可以通过让父 Controller 通过您创建的定义良好的 API 与子 Controller 对话来实现。这个想法是,您希望通过让每个各自的 Controller 尽可能少地了解彼此来保持父指令和子指令之间的松散耦合,但仍然有足够的知识来完成工作。

为此,从子指令中获取父指令,并让子指令在父 Controller 中注册自己:

子指令:

  require: '^parentDirective',
  controller: function(){
       this.someFunc = function() {...}
 },
  link: function(scope,element,attr, parentCtrl){
      parentCtrl.register(element);
 }

然后在你的parent指令中,实现register函数,并获取child的controller,需要的时候调用child的函数:

父指令:

  controller: function(){
      var childCtrl = undefined;
      this.register = function (element) {
          childCtrl = element.controller();
      }
     this.callChildFunc = function (){
            childCtrl.someFunc();
     }

  },
  link: function (scope,element){
        var ctrl = element.controller();
         ctrl.callChildFunc();
  }

关于javascript - 从它的父[angularJS]触发子指令中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27698454/

相关文章:

javascript - 指令链接函数中未定义的范围变量

javascript - AngularJS - 路由不起作用

javascript - angular 的 ui-router 似乎正在缓存解析。当我不想要它的时候

angularjs - Angular ui-router 解析父状态

javascript - 使用 Angular JS 中的 CKEditor 内容更新文本区域值

angularjs - 如何将 'replace' 功能用于自定义 AngularJS 指令?

javascript - 从 testcafe 中打开的第 N 个模态中选择确定按钮

javascript - 使用 gtk3 在 Seed-3.2 javascript 中使用 cairo 进行绘图

javascript - 带 Bootstrap 3 的 Accordion

javascript - angularjs ui-view元素不呈现内容