我在 HTML 的多个位置使用了 ng-include src
指令。每个 ng-include
都在为自己创建一个独立的作用域,这显然给我带来了很多麻烦。
例如。
<div ng-controller="parent">
<div ng-include src="'id1'">
</div>
<div ng-include src="'id2'">
</div>
<div ng-include src="'id2'">
</div>
</div>
在上面提到的 html 中,创建了 4 个范围。 1 个在定义了 controller
的父级,3 个在每个 ng-include src
中默认创建。
是否有可能阻止 ng-include
为自己创建一个独立的作用域?如果不可能,那么是否有解决方法?
最佳答案
你需要创建一个你自己的指令,它可以在没有隔离范围的情况下加载指定的模板。
HTML
<div ng-controller="parent">
<div my-directive template-path="id1">
</div>
<div my-directive template-path="id2">
</div>
<div my-directive template-path="id2">
</div>
</div>
指令
.directive('myDirective', function() {
return {
restrict: 'AE',
templateUrl: function(ele, attrs) {
return attrs.templatePath;
}
};
});
关于javascript - 防止 `ng-include` 创建隔离作用域。 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29115207/