Generate HTML string from AngularJS template string

前端 未结 2 844
陌清茗
陌清茗 2021-02-20 09:00

I have angularjs template as a string including \"ng-repeat\" and other directives. I want to compile it in the controller to produce the result HTML as string.

Example

2条回答
  •  爱一瞬间的悲伤
    2021-02-20 09:40

    For this purpose I made myself a directive couple of projects ago:

    angular.module('myApp')
    
    .directive('ngHtmlCompile', ["$compile", function ($compile) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.$watch(attrs.ngHtmlCompile, function (newValue, oldValue) {
                    element.html(newValue);
                    $compile(element.contents())(scope);
                });
            }
        }
    }]);
    

    and then for example:

    or even the string can be dynamic:

提交回复
热议问题