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

Mat*_*ood 3 javascript angularjs angularjs-directive

所以当我require: '^ParentCtrl'在child子指令中使用directive属性时,我总是反向完成.使用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;
                }

            };
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

儿童指令:

'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 () {...};
        }
    })
Run Code Online (Sandbox Code Playgroud)

pix*_*its 5

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

要实现这一点,需要来自子指令的parent指令,并让子指令将自己注册到父控制器:

儿童指令:

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

然后在你的父指令中,实现register函数,并获取子控制器,并在需要时调用子函数:

父指令:

  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();
  }
Run Code Online (Sandbox Code Playgroud)

  • 你说松散地结合指令,但你的例子似乎非常紧密耦合. (4认同)