AngularJS在重新编译动态html时删除旧的$ watchers [英] AngularJS Remove old $watchers when re-compiling dynamic html

查看:86
本文介绍了AngularJS在重新编译动态html时删除旧的$ watchers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AngularJS应用程序,该应用程序用于动态构建页面(从Server中检索XML并通过读取XML构建页面或表单来获取XML),因此我们必须构建的几个页面彼此相关,并且可以通过负数生成下一个",上一个"按钮.

I have an AngularJS application that used to Build Pages dynamically (retrieve an XML from Server and by reading that XML building pages or forms) for an XML we have to build few pages all are related with each other and can be negative via 'Next' , 'Previous' buttons.

要实现我们有类似的东西,

to implement that we have something like,

<div>
   <form name="myController.mainForm" novalidate>
      <div my-dynamic="myController.dynamicHtml"></div>
   </form>
</div>

herer myDynamic是指令,它处理生成的html,并且当我们必须导航到另一个页面时,我们为该页面生成新的HTML并将其分配给myController.dynamicHtml

herer myDynamic is directive, which deals with generated html and when we have to navigate to another page we generate new HTML for that page and assign it tomyController.dynamicHtml

在该指令中,我有类似的内容

and in that Directive I have something like this,

link: function postLink(scope, element, attrs) {
    scope.$watch(attrs.myDynamic, function (html) {
        element.html(html);
        $compile(element.contents())(scope);
    });
}

现在每个页面中都有许多输入控件(或指令),并且每个控件都有很少的绑定,这些绑定增加了观察者的数量.

Now in each page I have number of input controls(or directives), and each have few bindings that that adds to number of watchers.

我注意到,如果我 negative 导航到另一页,则直到my-dynamic指令从作用域中移除之前,前几页上的观察者都不会被破坏.

I have notice that if I negative navigate, to another page, watchers on previous pages not getting destroyed, until my-dynamic directive gets removed from scope.

当我们再次编译HTML时,我需要做的是确保上一页的手表被销毁.

What I need to do to make sure that watches on previous page gets destroyed when we again compile the HTML.

推荐答案

每次$compile服务每次都将某项链接到某个范围时,就会添加观察者.这就是为什么ng-repeatng-switchng-viewng-includeng-if之类的指令都创建新的子作用域的原因.它们链接到子作用域,并在销毁已编译的DOM时销毁该作用域.使用 scope.$ new

Everytime the $compile service links something to a scope, it adds watchers. That is why directives such as ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes. They link to the child scope and destroy that scope when destroying the compiled DOM. Use scope.$new and scope.$destroy.

link: function postLink(scope, element, attrs) {
    var newScope;
    scope.$watch(attrs.myDynamic, function (html) {
        if (newScope) {
            newScope.$destroy();
        };
        element.empty();
        if (html) {
            element.html(html);
            newScope = scope.$new()
            $compile(element.contents())(newScope);
        };
    });
}

这会创建并破坏更改后的子作用域.

This creates and destroys a child scope on changes.

这篇关于AngularJS在重新编译动态html时删除旧的$ watchers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆