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可見。我意識到我可以明確地聲明,但我寧願知道如何正確地做到這一點。
是的,這將是一段路要走。 – Beyers
我已經嘗試將這種方法應用於我的代碼,但它似乎與ng-repeat(或可能ng-transclude包裝我的孩子>應用。 – Bedrock
我應該在OP中提到取代:true和a transcluded div在模板中包裝指令 –
Bedrock