AngularJS:指令隔离范围 - 范围变量未定义

标签 angularjs angularjs-directive angularjs-scope

请有人能解释一下,为什么 attrDir 的范围变量可见,而 oneWay 不可见? 我认为 scope:{} 也是孤立的。

angular.module('test', []);

angular.module('test').directive('attrDir', attrDir);

function attrDir(){
    return {

        scope: true,

        link: function(scope){
          scope.hello = 'attrDir';
        }

    };
}

angular.module('test').directive('oneWay', oneWay);

function oneWay(){
    return {

        scope: {
          data: '<?'
        },

        link: function(scope){
          scope.hello = 'oneWay';  
        }

    };
}

hello 只会在 attr-dir 中呈现。

<attr-dir>
  <span>{{hello}}</span>
</attr-dir>
<one-way>
  <span>{{hello}}</span>
</one-way>

这是一个笨蛋:https://plnkr.co/edit/2CM4vVRshWuJvaBj2q8T?p=preview

谢谢。

最佳答案

首先,您观察到的与< 无关。绑定(bind)。

问题是表达式 {{hello}}在这两个指令中,不是这些指令模板的一部分。对于这些元素,绑定(bind)规则是不同的。

Angular 自动为 {{hello}} 创建链接函数表达式。但是在您的情况下,评估这些链接功能的范围是不同的。

您可能期望的是:

            rootScope
         /             \
        /               \
attr-dir-new-scope  one-way-isoloate-scope
      /                   \
     /                     \
{{hello}}               {{hello}}

然而,根据this comment in source :

// We only pass the isolate scope, if the isolate directive has a template,
// otherwise the child elements do not belong to the isolate directive.

真实的画面是这样的:

             root scope
         /             \    \
        /               \    \
attr-dir-new-scope       \    one-way-isoloate-scope
      /                   \
     /                     \
{{hello}}               {{hello}}

因此在您的示例中,第一个指令 <attr-dir>不创建隔离范围,而是创建新范围,因此当链接 Angular 将这个新范围传递给指令的链接功能时:

link: function(scope){
     scope.hello = 'attrDir';
}

以及为 {{hello}} 创建的链接函数表达。这就是为什么当您在链接函数中添加一个值时,它在表达式链接函数中可用。

但是你的第二个指令<one-way>创建 isolate scope 并且根据我上面提到的评论,指令的链接函数得到 isolate scope 它应该的,但是表达式的链接函数收到 不同的范围(您的示例中的根范围)。所以你要添加 hello不同范围的值(value)。这就是该值未定义的原因。

关于AngularJS:指令隔离范围 - 范围变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728977/

相关文章:

javascript - 使用转义键关闭模态的 Angular 指令

javascript - angularjs 如何序列化对象

javascript - 改进 Angular 中的 ng-repeat(只读 html 表格)渲染性能

javascript - Controller 函数在用作插值时被调用两次

javascript - 绑定(bind)到 Controller 范围的工厂中的修改数据,它不会更新

AngularJS 在嵌套的 ngRepeat 中访问 $first of ngRepeat parent

javascript - HTML 页面看不到 AngularJS 模块

javascript - AngularJS 指令 templateUrl 在加载文件 URL 时返回 400

javascript - 带有 UI Bootstrap 指令的 ng-bind-html

javascript - 无法将 eval() 与 Angular 一起使用