简体   繁体   English

在自定义指令中时,AngularJS模板变量未呈现

[英]AngularJS template variables not rendering when inside custom directive

I'm having an issue with a custom angular directive. 我在使用自定义角度指令时遇到问题。 Basically, in the example below, the variable "name" will render correctly if outside of the scope of the directive, but not when inside the directive. 基本上,在下面的示例中,如果变量“名称”超出指令范围,则不会正确呈现,但如果不在指令范围内,则将正确呈现。

Template: 模板:

<div ng-controller="swygController">
  <div swyg="example" edit="load(id)">
    {{name}}
  </div>
  {{name}
</div>

Directive: 指示:

swyg.directive('swyg', function(){
  return {
    restrict: 'A',
    scope: {
      edit: '&'
    },
    compile: function(elm, attr){
      // Code
    },
    controller: function($scope, $element, $attrs) {
     // Code
    }
  };
});

I've tested this with the compile and controller directive functions empty (to rule out something in my directive causing the issue) and get the same result. 我已经用compile和controller指令函数为空(以排除我的指令中引起问题的东西)进行了测试,并获得了相同的结果。

I'm fairly certain it's a scope issue, but can't figure out how to resolve it. 我相当确定这是一个范围问题,但无法弄清楚如何解决它。 It seems like I somehow need to allow the directive to inherit the controller's scope? 看来我某种程度上需要允许指令继承控制器的作用域? I assumed since the directive is inside the controller, it'd be fine. 我假设由于指令位于控制器内部,所以很好。

Has anyone else run into this? 还有其他人遇到吗?

Thanks for your help! 谢谢你的帮助!

As soon as you declare scope within a directive it is then an isolated scope and therefore variables from parent scope are not the same. 在指令中声明scope后,它即成为隔离的作用域,因此父作用域中的变量并不相同。

There are several ways to approach: 有几种方法可以解决:

One is using parent scope in expression. 一种是在表达式中使用父范围。 Nested scopes become nested in parent objects so you can do: 嵌套作用域嵌套在父对象中,因此您可以执行以下操作:

{{$parent.name}}

If nesting is 2 levels deep would be able to use $parent.$parent.name but this approach gets ugly 如果嵌套深度为2级,则可以使用$parent.$parent.name但是这种方法很难看

Or pass the variable to directive as an attribute, and include that in directive scope the same way you are doing with edit 或将变量作为属性传递给指令,并以与edit相同的方式将其包括在指令范围内

scope: { }

creates an isolated scope, meaning you can not access the parent scope and everything defined on it. 创建一个隔离的作用域,这意味着您无法访问父作用域及其上定义的所有内容。

You could use $parent.name to access the parent scope name variable. 您可以使用$ parent.name访问父作用域名称变量。 But I wouldn't recommend traversing the scope using $parent. 但是我不建议使用$ parent遍历作用域。

Instead pass the name as an attribute to your directive. 而是将名称作为属性传递给指令。

I've created a plunker to demonstrate how to do this: http://plnkr.co/edit/NGNMfkgNMooq0Sul6HPH?p=preview 我创建了一个插件来演示如何执行此操作: http ://plnkr.co/edit/NGNMfkgNMooq0Sul6HPH?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM