在我的情况下,如何将 html 内容添加到我的 dom 中

How to add html content into my dom in my case?

本文关键字:我的 添加 dom 情况下 html      更新时间:2023-09-26

我正在尝试让我的指令起作用。目标是在用户单击按钮时添加一堆 html。

我有类似的东西

.html

<a href='' test-product>click here</a>

.JS

angular.module('myApp').directive('testProduct', ['$compile',
    function($compile) {
        return {
            restrict: 'A',
            link: function(scope, elem) {
                var include = '<div ng-include="test/product.html"></div>'
                elem.bind('click', function() {
                    elem.append($compile(include)(scope));
                })
            }
        };
    }
]);

产品.html

<div>
   bunch of html here...
</div>

出于某种原因,它不会按预期添加产品 html 内容。我在这里做错了什么吗?

谢谢!

错误是ng-include需要一个包含字符串的变量。

正确的方法是这样做(注意添加的引号):

var include = '<div ng-include="''test/product.html''"></div>'

旁注:每次单击元素时,它都会添加ng-include。这是你期望发生的事情吗?