元素.自定义指令'中的replaceWith链接只在第一次调用时起作用

element.replaceWith in a custom directive's link only work at first time called

本文关键字:第一次 调用 起作用 链接 replaceWith 指令 自定义 中的 元素      更新时间:2023-09-26

我是Angularjs的新手,不太了解幕后的东西。基本上,我想创建一个'E'扭结指令,基于控制器中的数据,我动态创建html,就像一个完整的'表'的东西,以取代指令。

在我的html文件中的指令是这样的:
<matrixrows></matrixrows>
我的指令代码是这样的:
angular.module('matrix', [.....])
.directive('matrixrows', [..., function (...) {
        return {
            restrict: 'E',
            replace: true,
            require: '^matrix',
            link: function (scope, element, attr, ctrl) {
                ......... 
                scope.$watch('currentPage', function (newValue, oldValue) {
                    if (newValue && newValue != oldValue) {
                        var html = "";
                        .......................
                        here is the code to generate the html
                        .......................
                        element.replaceWith(html);
                    }
                });
             }
    }])

通过观察currentPage的变化,我重新创建html并替换指令标签。当我第一次改变'currentPage', 元素。replacewith (html)工作正常。然后我改变'currentPage angin,观看功能将被触发,但元素。replacewith (html)将不起作用。

然后我进入Angularjs源代码,我发现,在第一个时间元素之后。replaceWith的执行,元素[0]parentNode变成null,这导致replaceWith崩溃。

有人知道怎么让它工作吗?

看起来您试图多次替换相同的元素。但一旦被替换,它就消失了。为了解决这个问题,将currenthhtml存储在一个变量中。像这样:

        link: function (scope, element, attr, ctrl) {
            ......... 
            var currentElement = element;
            scope.$watch('currentPage', function (newValue, oldValue) {
                if (newValue && newValue != oldValue) {
                    .......................
                    var html = "";
                    here is the code to generate the html
                    .......................
                    var replacementElement = angular.element(html);
                    currentElement.replaceWith(replacementElement);
                    currentElement = replacementElement;
                }
            });
         }

你应该在生成的html字符串上使用$compile(…)

,

    link: function (scope, element, attr, ctrl) {
        ......... 
        var currentElement = element;
        scope.$watch('currentPage', function (newValue, oldValue) {
            if (newValue && newValue != oldValue) {
                .......................
                var html = "";
                here is the code to generate the html
                .......................
                var replacementElement = $compile(html)(scope);
                currentElement.replaceWith(replacementElement);
                currentElement = replacementElement;
            }
        });
     }