角度指令的范围继承

时间:2013-10-01 08:44:28

标签: javascript angularjs angularjs-directive angularjs-scope

我使用angular指令创建了一个制表符控件。它由标签标签项指令组成,包含新范围和标签项标题标签项目正文< / strong>未声明范围的指令。

如果我理解正确,这些指令使用tab-item指令的范围,因为它们被放在其中。但是当我尝试获取在tab-item范围内声明的标记属性索引时,它是未定义的。

app.directive('tabItemHeader', function(){
return {
    require: '^tabItem',
    transclude: true,
    template: '<div ng-click="$parent.setCurrentTab(index)" ng-transclude></div>',
};});

app.directive('tabItemBody', function(){
return {
    require: '^tabItem',
    transclude: true,
    template: '<div ng-show="index==$parent.currentTabIndex"><div ng-transclude></div></div>'
};});

我已经创建了一个插件http://plnkr.co/edit/HkXIOt8FKMw4Ja2GZtF1?p=preview来演示它。

有什么问题?

2 个答案:

答案 0 :(得分:5)

(编辑)在评论中的对话之后,我想出了一个更好的解决方案。这是修改后的插件:

http://plnkr.co/edit/djNk8PPzXvngZOvAirMu?p=preview

此实施的关键点是:

  • 每个指令都会转换其内容。这意味着,即使是最里面的指令也可以访问外部作用域,如预期的那样。所以不再$parent.$parent...可怕。

  • 每个指令都有一个孤立的范围。根据文件,孤立的范围与被抄袭的范围并排;因此,指令的所有私有状态(在本例中为活动选项卡,每个tabItem的索引和一些特定于指令的函数)都保存在隔离的范围内。

  • 指令通过控制器进行通信。此模式需要顶级“协调员”(此处tab表示所有后代指令,tabItem表示tabItemHeadertabItemBody

顺便说一下,如果你想要标签,我建议使用Angular UI。


这是一个疯狂的益智游戏。

问题的原因是tabItem指令没有理由转录其内容;这种翻译创造了一个兄弟范围,完全搞砸了你的逻辑!

因此答案很简单:从tabItem指令中删除这些行:

// REMOVE THEM!!!
transclude: true,
template: '<div ng-transclude></div>',

带有这些行的plunkr注释掉了打印范围ID:http://plnkr.co/edit/bBfEej145s1YjcE9n3Lj?p=preview(这有助于调试;看看当包含这些行时会发生什么,模板和链接器函数会看到不同的范围!)

你的傻瓜分叉,用这些线条注释掉:http://plnkr.co/edit/tgZqjZk0bRCyZiHKM0Sy?p=preview

答案 1 :(得分:4)

http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/

这个网站很好地解释了范围继承。

基本上,如果您将范围部分添加到您想要的指令中,您有几个选项:

scope: false # this inherits the parent scope and allows upstream and downstream traffic (parent <=> child)
scope: true # this inherits the parent scope and allows downstream traffic (parent => child)
scope: {} # this does not inherit and creates the directive's very own scope (you can still inherit by specifying what you want to come down)

通过最后一个选项指定要继承的范围的更多详细信息:What is the difference between & vs @ and = in angularJS