嵌套指令破角嵌套、指令

2023-09-13 05:11:18 作者:骚不起咱就矜持点

每当我用自身内部指令,页面冻结,并吃掉越来越多的CPU和RAM,直到标签挂起。

Whenever I use a directive within itself, the page freezes, and eats up more and more CPU and RAM until the tab hangs.

我已经是这样的。

Application.Directives.directive('somed', function() {
    return {
        restrict: 'E',
        // Load the template from a separate HTML file
        templateUrl: 'directives/somed/view.html',
        replace: true
    };
});

和模板,像

<div ng-if="nonexistent">
    <somed></somed>
</div>

这应该的从不的(如果我把一个div标签,而不是somed的NG-如果计算结果为假,所以不显示任何内容,这就是确认)加载嵌套指令。然而,浏览器挂起就可以了。

Which should never load the nested directive (the ng-if evaluates to false, so no content is shown. This is confirmed if I put a div tag instead of somed). Yet, the browser hangs on it.

怎么来了,哪能prevent呢?

How come, and how can I prevent it?

推荐答案

借助文档 NG-如果 说:

此外, ngIf 再现利用其编译状态的元素。

Also, ngIf recreates elements using their compiled state.

此外,由于模板 somed 引用 somed ,这将不能够成功编译。这将解释这个问题。

And since template for somed references somed, it'll not be able to successfully compile. That will explain the problem.

有$ P $的几种方法pventing它,这取决于你的需求。

There are several ways of preventing it, depending on your needs.

您可以包括模板使用的 NG-包括 并把模板在你的 $ templateCache 。您可以动态地设置 HTML 在此指令被称为在链接功能和元素然后使用 $编译 服务间preT里面的(可能递归)指令。 You can include the template using an ng-include and putting the template in your $templateCache. You can dynamically set the html of the element on which this directive is being called in the link function and then use the $compile service to interpret the (possibly recursive) directives inside it.