我指的是 AngularJS 学习 Material ,并试图实现“具有隔离范围的指令”,但它不起作用。请在下面找到给定的代码片段,我已经完成了。
HTML:
<body ng-app="myApp">
<div ng-init="myProperty = 'wow, this is cool'">
Surrounding scope: {{ myProperty }}
<div my-inherit-scope-directive>
Inside an directive with inherited scope: {{ myProperty }}
</div>
<div my-directive>
Inside myDirective, isolate scope: {{ myProperty }}
<div>
</div>
</body>
JS:
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
restrict: 'A',
scope: {}
};
});
app.directive('myInheritScopeDirective', function() {
return {
restrict: 'A',
scope: true
};
});
Angular JS:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
实际输出:
Surrounding scope: wow, this is cool
Inside an directive with inherited scope: wow, this is cool
Inside myDirective, isolate scope: wow, this is cool
预期输出:
Surrounding scope: wow, this is cool
Inside an directive with inherited scope: wow, this is cool
Inside myDirective, isolate scope:
不同之处在于输出的最后一行。
我同意,SO 上已经出现了几个类似标题的问题。我经历过他们,相信我,没有人能回答我的问题。因此,考虑提出针对我的要求的问题。
最佳答案
根据 Angular's compile.js
文档注释,(用于 scope
指令的属性)
{...}
(an object hash): A new "isolate" scope is created for the directive's template. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope. Note that an isolate scope directive without atemplate
ortemplateUrl
will not apply the isolate scope to its children elements.
而且,这里没有
template
/templateUrl
所以它是这样工作的。这是your working example with template
编辑 : 这是一个 closed github issue regarding this其中解释为什么部分 :
来自 gkalpak 的评论
Indeed it doesn't sound like a good practice to rely on a component-directive's internals from the HTML (i.e. have child DOM elements that assume certain things about a directive on their parent) - if the contents are specific to a component, they belond in it's template.
In that respect, it does sounds reasonable.
编辑 2 :这是作为
Angular@1.2.0 timely-delivery (2013-11-08)
的一部分引入的因此它无论如何都可以在之前的版本中使用。根据 CHANGELOG :(v1.2.0 重大变化)
$compile:
- due to d0efd5ee, Child elements that are defined either in the application template or in some other directives template do not get the isolate scope. In theory, nobody should rely on this behavior, as it is very rare - in most cases the isolate directive has a template.
关于AngularJS 指令隔离范围不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042861/