在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/