Generate HTML string from AngularJS template string

前端 未结 2 842
陌清茗
陌清茗 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:

    <div ng-html-compile='<div ng-repeat="item in items">{{item.data}}</div>'></div>
    

    or even the string can be dynamic:

    <div ng-repeat="item in items" ng-html-compile="item.template">
    </div>
    
    0 讨论(0)
  • 2021-02-20 09:57

    Give this a whirl:

    var template = angular.element('<div ng-repeat="item in items">{{item.data}}</div>');
    var linkFunction = $compile(template);
    var result = linkFunction($scope);
    $scope.$apply();
    
    console.log(template.html());
    
    0 讨论(0)
提交回复
热议问题