2014-12-11 67 views
4

我有一對嵌套的指令。我試圖保持一致並使用controllerAs語法。但我正在努力尋找一種乾淨的方式讓孩子們調用父母方法,這種父母方法不包括父母在其範圍上放置看似隨機的功能。在指令中使用控制器的語法訪問父項方法

angular.module('app', []) 

.directive('parent', function(){ 
    return { 
     restrict: 'EA', 
     controller: 'ParentController', 
     controllerAs: 'parentCtrl', 
    } 
}) 
.directive('child', function(){ 
    return { 
     restrict: 'EA', 
     require: '^parent', 
     controller: 'ChildController', 
     controllerAs: 'childCtrl' 
    } 
}) 
.controller('ParentController', function($scope){ 
    var ctrl = this; 

    ctrl.type = "hot"; 
    ctrl.nonInheritedFunction = nonInheritedFunction; 
    $scope.inheritedFunction = inheritedFunction; // <-- trying to avoid this 

    function nonInheritedFunction(type){ 
     ctrl.type = type; 
     if(ctrl.type == 'cold'){ 
      //... do some Parent related things 
     } 
    } 
    function inheritedFunction(type){ 
     // to illustrate that it does the same thing. Not a solution 
     ctrl.nonInheritedFunction(type); 
    } 
}) 
.controller('ChildController', function($scope){ 
    var ctrl = this; 

    ctrl.doAction = doAction; 

    function doAction(action){ 
     if(action == 'flip_temperature'){ 
      // bah 
      $scope.parentCtrl.nonInheritedFunction('hot'); 

      // much cleaner feeling 
      $scope.inheritedFunction('hot'); 

      // wishing I could do something like 
      // ctrl.nonInheritedFunction('hot'); 
     } 
    } 

    /** 
    * template has access to type through `parentCtrl.type` 
    * and the function through `parentCtrl.nonInheritedFunction` 
    * 
    * The only access the ChildController has is `$scope.parentCtrl.type` 
    * Is there a way to keep $scope out of the equation? 
    */ 

}) 

回答

0

transclude:真在父母指導和手動傳入transclude功能範圍在父母的您的鏈接功能。 假設,如果該指令創建一個隔離範圍,則該隔行範圍現在是隔離範圍的子級。跨越式隔離示波器不再是兄弟姐妹。 transcluded範圍的$ parent屬性現在引用隔離範圍。

0

在角度> 1.3中,您可以使用bindToController將範圍變量附加到控制器。

比方說您有一個綁定到範圍父母的功能

scope: { 
    onSomethingHappen: '&parentFunction' 
}, 
controller: 'DirectiveController', 
controllerAs: 'vm', 
bindToController: true 

你能叫:this.onSomethingHappen()控制器

0

上必須使用孩子指令嵌套,所以你可以訪問外部控制器。

<parent > 
<child > 

</child></parent> 
相關問題