javascript - 具有隔离范围的 Angularjs 指令需要澄清

标签 javascript angularjs angularjs-directive angularjs-scope

编辑:

这个plunker中有一个功能示例:

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

外部范围有 $scope.name = 'Donald'

所有指令声明为:

<directive-name binding="name">

这是一个多部分问题。我试图更好地理解具有监视或绑定(bind)到外部范围变量的独立范围。

使用非隔离作用域指令,一切正常:

  // [WORKS]
  .directive('noScopeWithWatch', function(){
    return {
      restrict: 'E',
      link: function(scope, lElement, attrs) {
        scope.$watch(attrs.binding, function(name){
          lElement.text('Hello ' + name);
        });
      }
    };
  })
  // returns Hello Donald

令人困惑的部分是当我尝试隔离范围并保持绑定(bind)时。所以我要求的是澄清为什么以下示例有效,而其他示例无效。

如果我只是添加带有“正常”绑定(bind)的范围隔离,它会失败:

  // 1. [FAILS]
  .directive('scopeWithWatch', function(){
    return {
      restrict: 'E',
      link: function(scope, lElement, attrs) {
        scope.$watch(attrs.binding, function(name){
          lElement.text('Hello ' + name);
        });
      },
      scope: {                                   // new content
        binding: '='                             // new content
      }                                          // new content
    };
  })
  // returns Hello undefined

但是,在 watch 中使用绑定(bind)变量作为字符串使其工作:

  // 2. [WORKS]
  .directive('scopeWithWatchString', function(){
    return {
      restrict: 'E',
      link: function(scope, lElement, attrs) {
        scope.$watch('binding', function(b){     // new content
          lElement.text('Hello ' + b);
        });
      },
      scope: {
        binding: '=' 
      }
    };
  })
  // returns Hello Donald

当使用绑定(bind)变量作为对象失败时:

  // 3. [FAILS]
  .directive('scopeWithWatchObject', function(){
    return {
      restrict: 'E',
      link: function(scope, lElement, attrs) {
        scope.$watch(binding, function(b){       // new content
          lElement.text('Hello ' + b);
        });
      },
      scope: {
        binding: '='
      }
    };
  })
  // Does not work at all
  // Console output - ReferenceError: binding is not defined

尝试在隔离范围内引用绑定(bind)变量也不起作用,但至少不会导致异常:

  // 4. [FAILS]
  .directive('scopeWithWatchScopeObject', function(){
    return {
      restrict: 'E',
      link: function(scope, lElement, attrs) {
        scope.$watch(scope.binding, function(b){  // new content
          lElement.text('Hello ' + b);
        });
      },
      scope: {
        binding: '='
      }
    };
  })
  // returns Hello undefined

事实证明,在模板中使用 mustaches 中的绑定(bind)变量是可行的:

  // 5. [WORKS]
  .directive('scopeWithTemplate', function(){
    return {
      restrict: 'E',
      template: 'Hello {{binding}}',     // new content and linker removed
      scope: {
        binding: '='
      }
    };
  })
  // returns Hello Donald

但尝试将它们用作链接器中的 mustache 不会。

  // 6. [FAILS]
  .directive('scopeWithWatchStringUsingMustashes', function(){
    return {
      restrict: 'E',     
      link: function(scope, lElement, attrs) {        // new content
        scope.$watch('binding', function(){           // new content
          lElement.text('Hello {{binding}}');         // new content  
        });                                           // new content
      },                                              // new content
      scope: {
        binding: '='
      }
    };
  })
  // returns Hello {{binding}}

这里是 plunker:

http://plnkr.co/edit/GFQGP0q3o9RjLAlRANPS?p=preview (我目前的版本是 78,如果你想在你的答案中使用它,请 fork。)

有人可以向我解释为什么有些示例有效而其他示例无效。

最佳答案

对此有一个简单的答案,适用于此处的所有示例。 $compile 上的 Angular 文档解释了这一点,但很容易引起误解。独立作用域的全部目的是创建一个仅由声明它的指令使用的作用域。为此,将创建一个新变量,将值存储为父作用域的别名。

主要有3种定义类型:@, =, &

@ or @attr - bind a local scope property to the value of DOM attribute. The result is always a string since DOM attributes are strings.

= or =attr - set up bi-directional binding between a local scope property and the parent scope property of name defined via the value of the attr attribute.

& or &attr - provides a way to execute an expression in the context of the parent scope.

@= 之间的唯一区别是双向支持。 = 定义仍将返回字符串结果。

因此,您所拥有的依次是:

<醇>
  • 独立作用域不提供对 attrs 集合的访问,它只能访问它自己的独立作用域项。这是行不通的,因为范围内没有 attrs 对象。
  • 按预期工作,binding='name'binding: '=' 匹配并且 'binding' 可作为别名访问在隔离范围内。
  • 失败,因为 attr 始终是字符串,它们不是 javascript 对象。
  • 失败,

    The 'isolate' scope differs from normal scope in that it does not prototypically inherit from the parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

  • 有效,原因与 2 相同。绑定(bind)正确匹配。模板由 $compile 自动处理。
  • 失败,因为 lElement.text 就是文本。在文本分配中使用表达式需要在将文本发送到 dom 之前执行额外的手动编译步骤,否则 {{}} 表达式将被视为纯文本。
  • 关于javascript - 具有隔离范围的 Angularjs 指令需要澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22294219/

    相关文章:

    AngularJS 服务/ Controller 不更新 Angular-leaflet-directive 映射

    javascript - 在 Bootstrap 行中垂直居中按钮

    javascript - 在悬停/鼠标悬停时启动 youtube 视频

    javascript - 当我尝试使用 ng-init 时,Angular JS : Controller not working. 一切都很完美

    javascript - 如何在另一个指令中调用一个指令函数?

    javascript - 使用同一 Angular Directive(指令)的多个副本时,变量不能独立运行

    AngularJS指令范围不更新它的模板

    javascript - 循环另一个文件中的字符串的最佳方法?

    javascript - 如何将多个前置日期存储到 localStorage?

    angularjs - Chrome 打包应用程序 AngularJS 样板模板