javascript - 如何理解AngularJS中指令的scope属性?

标签 javascript angularjs angularjs-scope directive

在AngularJS指令的指导教程中,指令对象可以具有scope属性。它定义了指令的范围。

虽然范围属性值可能为 true,但以下是范围的解释:( link of the scope definition )

true: A new child scope that prototypically inherits from its parent will be created for the directive's element. If multiple directives on the same element request a new scope, only one new scope is created.

我对粗体的句子感到困惑。同一元素上的多个指令如何使用相同的作用域?

最佳答案

根据我的说法,这意味着将根据元素而不是根据指令创建作用域。

因此,范围将自动在指令之间共享,并且不会为每个指令创建不同的副本。

在此链接中https://www.bennadel.com/blog/2729-don-t-blindly-isolate-all-the-scopes-in-angularjs-directives.htm

他们提到:

如果您使用 AngularJS 1.2,下一个障碍是您无法将两个隔离范围指令应用于同一元素。看看下面的代码。它所做的只是将两个指令应用于同一个元素。而且,这些指令除了需要隔离作用域之外什么也不做。

因此,如果您在两个指令中使用相同的作用域变量,则会抛出以下错误

Error: error:multidir

Multiple Directive Resource Contention

Multiple directives [bnThat, bnThis] asking for new/isolated scope on

因此,对于这种情况,以嵌套方式嵌入或放置指令可以完成这项工作。

下面的代码片段给出了我上面提到的示例。

// Create an application module for our demo.
var app = angular.module("Demo", []);
// -------------------------------------------------- //
// -------------------------------------------------- //
// I request an isolate scope directive.
app.directive(
  "bnThis",
  function() {
    // Return the directive configuration. Notice that we are creating an
    // isolate scope, even though we are not binding any expressions.
    return ({
      link: angular.noop,
      restrict: "A",
      scope: {}
    });
  }
);
// -------------------------------------------------- //
// -------------------------------------------------- //
// I request an isolate scope directive.
app.directive(
  "bnThat",
  function() {
    // Return the directive configuration. Notice that we are creating an
    // isolate scope, even though we are not binding any expressions.
    return ({
      link: angular.noop,
      restrict: "A",
      scope: {}
    });
  }
);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="Demo">

  <p bn-this bn-that>
    Look at the console output.
  </p>

</div>

关于javascript - 如何理解AngularJS中指令的scope属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798409/

相关文章:

javascript - 如何直接在 HTML 页面中拍照(而不打开相机应用程序)?

javascript - NodeJS 没有序列化 ES6 Map

javascript - 获取 G Suite 中给定用户列表的用户事件报告

javascript - 何时可以通过 Angular 2 使用模板引擎?

javascript - AngularJS - 当使用指令生成标记时,无法使用 ng-click 执行方法

angularjs - 新手 AngularJS Controller $scope 无法读取 undef 的属性

javascript - 如何检查范围是否隔离?

javascript - "hotkey string"的正则表达式

javascript - Controller 函数被多次调用

javascript - 将数据从 Node 发送到 Angular 以在 ng-repeat 中使用的正确方法。