角度指令的作用域继承

Scope inheritance for angular directives

本文关键字:作用域 继承 指令      更新时间:2023-09-26

我使用角度指令创建了一个选项卡控件。它由具有新作用域的选项卡、选项卡项指令和未声明范围的选项卡项标头、选项卡正文指令组成。

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

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>'
};});

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

怎么了?

(编辑( 在评论中的对话之后进行了一些思考,我想出了一个更好的解决方案。这是修改后的 plunk:

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

此实现的关键点是:

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

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

  • 指令通过控制器进行通信。这种模式需要一个顶级的"协调器"(这里是所有后代指令的tabtabItemHeadertabItemBodytabItem(。

顺便说一句,如果你想要标签,我会建议Angular UI。


这是一个疯狂的谜题游戏。

你问题的原因是tabItem指令没有理由排除它的内容;这种嵌入创造了一个同级范围,完全搞砸了你的逻辑!

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

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

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

你的 plunkr 分叉了,这些行被注释掉了:http://plnkr.co/edit/tgZqjZk0bRCyZiHKM0Sy?p=preview

> 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)

有关通过最后一个选项指定要继承的范围的更多详细信息:angularJS中的&与@和=有什么区别