【发布时间】:2015-09-21 19:22:46
【问题描述】:
我正在尝试从具有隔离范围的父自定义指令继承属性。在下面的示例中,我希望能够从 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 是可见的。我意识到我可以明确声明,但我宁愿了解如何正确地做到这一点。
【问题讨论】:
标签: angularjs