2015-09-21 118 views
0

我想從隔離範圍的父定製指令繼承屬性。在下面的示例中,我希望能夠通過myChild控制器或鏈接函數訪問myParent上的api屬性。我的最終目標是注入一個可由兒童和視圖控制器訪問的api實例。繼承與隔離範圍的角度父指令屬性

<my-parent api="parentInstance1"> 
    <my-child ng-repeat="field in ::data" 
     ng-attr-src="{{field.src||undefined}}" 
    </my-child>   
</my-parent> 

<my-parent api="parentInstance2"> 
    <my-child ng-repeat="field in ::data" 
     ng-attr-src="{{field.src||undefined}}" 
    </my-child> 
</my-parent> 

兩個指令的簡化版本看起來像這樣

app.directive('myParent', function() { 
    return { 
     transclude: true, 
     restrict: "E", 
     scope: { 
      api: '=?' 
     }, 
     template: '...', 
     controller: function ($scope, $attrs) { 

      // foo is injected from a factory instance 
      function foo () { 

      } 

      $scope.api = { 
       foo: foo 
      } 
     }, 
     link: function ($scope, $element, $attr) { 

     } 
    } 
}); 

app.directive('myChild', function() { 
    return { 
     require: "^myParent", 
     restrict: "E", 
     scope: { 
      api: '=?'     
     }, 
     template: "...", 
     controller: function ($scope) { 
      // I want to access $scope.api in link or controller    
     }, 
     link: function ($scope, $element, $attr) { 
      // I want to access $scope.api in link or controller 
     } 
    } 
}); 

我無法從子指令訪問$ scope.api但$ scope.parentInstance1和$ scope.parentInstance2可見。我意識到我可以明確地聲明,但我寧願知道如何正確地做到這一點。

回答

1

我不知道爲什麼你在my-parent引用parentInstance1parentInstance2my-child的屬性在myParent$scope,所以你可以參考實際$scope.api對象是myParent$scopemy-child指示標記的屬性然後在myChild指令的隔離範圍定義中引用該屬性的名稱。

<my-child inner-api="api"></my-child> 

..然後在子指令......

app.directive('myChild', function() {  
... 
scope: { 
    innerApi: '=?' 
} 
... 
controller: function($scope) { 
    $scope.innerApi // <- accessible in the controller 
} 

繼承人simplified fiddle ...

+0

是的,這將是一段路要走。 – Beyers

+0

我已經嘗試將這種方法應用於我的代碼,但它似乎與ng-repeat(或可能ng-transclude包裝我的孩子>應用。 – Bedrock

+0

我應該在OP中提到取代:true和a transcluded div在模板中包裝指令 – Bedrock