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

北城余情 提交于 2019-12-04 02:53:45

It looks like you're attempting to replace the same element several times. But once it's been replaced, it's gone. To solve this store the currentHtml in a variable. Something like this:

        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;
                }
            });
         }

You should be using $compile(...) on the generated html string.

ex:

    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;
            }
        });
     }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!