element.replaceWith在自定义指令的链接中仅在第一次调用时工作

Gis*_*way 9 javascript angularjs angularjs-directive

我是Angularjs的新手,在幕后不太了解.基本上我想创建一个'E'扭结指令,基于控制器中的数据我动态创建html,就像整个'table'一样,来替换指令.

我的html文件中的directve是这样的:

<matrixrows></matrixrows>
Run Code Online (Sandbox Code Playgroud)

我的指令代码是这样的:

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);
                    }
                });
             }
    }])
Run Code Online (Sandbox Code Playgroud)

通过观察currentPage的更改,我重新创建了html并替换了指令标记.当我第一次更改'currentPage'时,element.replaceWith(html)工作正常.然后我改变'currentPage angin,将触发观看功能,但是element.replaceWith(html)将不起作用.

然后我进入Angularjs源代码,我发现,在第一次执行element.replaceWith后,element [0] .parentNode变为null,这导致了replaceWith崩溃.

有谁知道如何使它工作?

Mit*_*hon 13

看起来你试图多次替换相同的元素.但是一旦它被取代,它就消失了.要解决这个问题,将currentHtml存储在一个变量中.像这样的东西:

        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;
                }
            });
         }
Run Code Online (Sandbox Code Playgroud)