2014-12-30 79 views
3

因此,在子指令中使用僞指令屬性require: '^ParentCtrl'時,我總是反向操作。使用require來調用父函數;不過,我需要做相反的事情。在父指令中觸發子指令中的函數[angularJS]

問:
如何觸發從父指令在孩子指示功能的執行。

注意: 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() {...}; 
     } 
    }) 

回答

5

這可能是通過一個良好定義的API具有父控制器聊到孩子控制器,你創建。這個想法是,你想通過讓每個控制器儘可能少地瞭解對方來保持父母和孩子之間的鬆散耦合,但仍然有足夠的知識來完成工作。

爲了實現這一目標,需要從孩子指令父指令,並讓孩子指令與父母的控制器註冊自己:

兒童指令:

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

然後,執行需要時註冊功能,並獲得孩子的控制器,並呼籲孩子的功能:

家長指令:

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(); 
    } 
+4

你說鬆散地耦合指令,但你的例子似乎非常緊密耦合。 – tic

2

你總是可以通過$手錶觸發它。只要傳入您想要查看的父範圍值並更改其值即可。

家長:

$scope.drawHotspots = false; 

模板:

  waHotspots the-trigger="drawHotspots".... 

兒童指令:

 localTrigger: '@' // Receive the value to watch 

     scope.$watch('localTrigger',function() { 
       // call drawHotspots if value is set to true 
     });