【问题标题】:Angularjs directive duplicates the elements inside itAngularjs 指令复制其中的元素
【发布时间】:2018-09-05 13:34:37
【问题描述】:
    (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;
                        };
               };

        }]);

})();

我有一个指令可以替换其中的元素。 我有一个奇怪的问题,它在指令中多次替换元素。

复制下面粗体行中不应该发生的元素。

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

请告诉我为什么元素重复,并告诉我如何避免它。

样本

实际

酷酷的

预计

很酷

【问题讨论】:

  • 它们是 'replace' 指令属性,它被标记为 deprecated 然后被删除。做被禁止的事情似乎是错误的......

标签: javascript angularjs angularjs-directive


【解决方案1】:

在我的情况下,以下指令仅替换内容一次。如果这不能解决您的问题,也许您可​​以提供一个小的工作示例左右。另请注意,如果您为指令使用隔离范围,则应提供模板,如 this 帖子中所述。

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

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 2014-09-02
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多