清除DOM后,Angular Js动态加载的指令仍处于活动状态

时间:2016-04-28 09:46:23

标签: javascript angularjs angularjs-directive dynamic-compilation

我有一个动态加载指令的下拉列表。当我选择“选项a”时,它会加载“指令a”,当我选择“选项b”时,它会加载“指令b”。但是,当第二个指令被加载并且DOM被新的指令覆盖时,angular似乎仍然会对刚删除的那个以及新的一个进行操作。

以下是我的代码中的代码段,以便您了解正在发生的事情。

    // change event on dropdown list
    function onSelection(e, args) {
        if (args) {
            ctl.build(args.type || "integer");
        }
    }


    /** build the relevant directive based on the type */
    function build(type) {
        type = type.toLowerCase();
        var directive = "<rep-"+type+"-control args='filter.args'></rep-"+type+"-control>";
        var control = $element.find("#control");

        // only compile the new control so we don't duplicate ng events on the outer directive
        control.html(directive);
        $compile(control.contents())($scope);
    }

这只是挂钩到change事件,并运行“build”。 Build接受一个给定的参数(这是所选选项的值)并加载一个具有相同名称"<rep-option-control>"的指令。它将它加载到特定的DOM元素中,并编译该元素。

指令A的输入类型为“文本”,指令B的输入类型为“数字”。如果我首先加载指令B,然后加载指令A并在输入中输入内容(type ='text'),我会收到此错误:https://docs.angularjs.org/error/ngModel/numfmt?p0=test这清楚地表明我正在尝试将字符串内容输入到号码输入。

这意味着即使我运行control.html(directive)$compile,旧指令仍处于活动状态。

有没有人知道我怎么能阻止这个?

0 个答案:

没有答案