简体   繁体   中英

Angularjs directive duplicates the elements inside it

    (function () {

    'use strict';

    angular.module('product')
        .directive('sampledirective', ['$document') {
                return {
                    restrict: 'E',
                    replace: true,
                    scope: {
                        data: '=',
                        btnClick: '&'
                    },
                    link: function (scope, element, attr) {


                            var compiled = $compile(template)(scope);
                            angular.element(element).replaceWith(compiled);
                            element = compiled;
                        };
               };

        }]);

})();

I have a directive which replaces the elements inside it. I have a weird issue which replaces the elements mulitple time in the directive .

Duplicates the elements in the below bolded line which should not happen.

angular.element(element).replaceWith(compiled);

Please let me know why the elemenst are duplicated and let me know how to avoid it .

sample

Actual

cool cool

expected

cool

The following directive only replaces the content once in my case. If this dosn't solve your problem maybe you could provide a small working example or so. Also note that if you use an isolated scope for your directive you should provide a template, as stated in this post.

angular.module('product').directive("sampledirective", function ($compile) {
    return {
        template: '',
        restrict: 'E',
        scope: {
            data: "=data",
            btnClick: '&'
        },
        link: function (scope, element, attrs) {
            var template = "<div>foo</div>"
            var compiled = $compile(template)(scope);

            element.replaceWith(compiled);
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM