如何将 html 添加到 Angular 中?

How to add html into Angular in my case?

我正在尝试创建一个指令,在用户单击按钮时添加大量 html。

angular.module('myApp').directive('testProduct', function() {
        return {
            restrict: 'A',
            link: function(scope, elem) {
                var html;
                html = '<div>… a lot of html tags and contents………….'; 
                // a lot of html tags
                //I want to link to a html file like product.html 
                //instead of defining here.
                elem.bind('click', function() {
                    $('.product').remove();
                    elem.closest('div').append(html);
                })
            }
        };
    }
);

无论如何我可以 link 将 html 到另一个文件吗?喜欢 templateUrl:product.html?我不能在这里使用它,因为我只想在用户单击按钮时添加那些 html。

非常感谢!

在点击事件中创建一个类似<div ng-include="foo.html"></div>的元素并将其传递给angular.element。然后将其附加到 DOM。添加后使用注入的 $compile 服务。 $compile(dynamicIncludeElement)(scope).

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

                elem.bind('click', function() {
                    var compiledHtml = $compile(html)(scope);
                    elem.append(compiledHtml);
                })
            }
        };
    }
);

另一种选择是自己获取 HTML 并编译它。

angular.module('myApp').directive('testProduct', function($http, $compile) {
        return {
            restrict: 'A',
            link: function(scope, elem) {

                elem.bind('click', function() {

                    $http.get('product.html')
                        .success(function(data) {
                            var compiledHtml = $compile(data)(scope);
                            elem.append(compiledHtml);
                        }
                    );

                })
            }
        };
    }
);