问题描述
我想访问父指示的范围,但我似乎无法得到的设置正确的组合。这是可能的,是正确的做法?
I would like to access a parent directive's scope, but I can't seem to get the right combination of settings. Is this possible and is it the right approach?
我真的想避免把类似SOME_CONST(这会帮我做DOM通过控制流更新)中MyCtrl
I really want to avoid putting something like SOME_CONST (which would help me make DOM updates through control flow) in MyCtrl
<div ng-controller="MyCtrl">
<parent>
<child></child>
</parent>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.obj = {prop:'foo'};
}
myApp.directive('parent', function() {
return {
scope: true,
transclude: true,
restrict: 'EA',
template: '<div ng-transclude><h1>I\'m parent {{obj.prop}}<h1></div>',
link: function(scope, elem, attrs) {
scope.SOME_CONST = 'someConst';
}
}
});
myApp.directive('child', function() {
return {
restrict: 'EA',
template: '<h1>I\'m child.... I want to access my parent\'s stuff, but I can\'t. I can access MyCtrlScope though, see <b>{{obj.prop}}</b></h1> how can I access the <b>SOME_CONST</b> value in my parent\'s link function? is this even a good idea? {{SOME_CONST}}. I really don\'t want to put everything inside the MyCtrl',
}
});
请参阅此
感谢
推荐答案
通过 transclude:真正的
和范围:真正的
的父
指令创建了两个新领域:
With transclude: true
and scope: true
, the parent
directive creates two new scopes:
范围004是范围的结果:真正的
,和范围005 transclude的结果:真正的
。因为孩子
指令不创建一个新的范围,它采用transcluded范围005正如你从图中可以看到有从范围到005范围004无路径(除了通过私有财产$$prevSibling,它出现在$$ nextSibling的相反方向 - 但不要使用那些)
Scope 004 is a result of scope: true
, and scope 005 is a result of transclude: true
. Since the child
directive does not create a new scope, it uses transcluded scope 005. As you can see from the diagram there is no path from scope 005 to scope 004 (except via private property $$prevSibling, which goes in the opposite direction of $$nextSibling -- but don't use those.)
@ joakimbl的解决方案可能是最好的位置,但我认为这是比较常见的父指令的控制器上定义的API,而不是这个
定义属性:
@joakimbl's solution is probably best here, although I think it is more common to define an API on the parent directive's controller, rather than defining properties on this
:
controller: function($scope) {
$scope.SOME_CONST = 'someConst';
this.getConst = function() {
return $scope.SOME_CONST;
}
}
然后在孩子
指令:
link:function(scope,element,attrs,parentCtrl){
scope.SOME_CONST = parentCtrl.getConst();
},
这是标签
和面板
指令如何对角的主页工作(创建组件的例子)。
This is how the tabs
and pane
directives work on Angular's home page ("Create Components" example).
这篇关于在Transcluded指令访问父范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!