从AngularJS模板字符串生成HTML字符串

Generate HTML string from AngularJS template string

本文关键字:字符串 HTML AngularJS      更新时间:2023-09-26

我有angularjs模板作为一个字符串,包括"ng repeat"和其他指令。我想在控制器中编译它,以产生字符串形式的结果HTML。

关于我想在Angular中应用的示例:

Input:
-------
var template = '<div ng-repeat="item in items">{{item.data}}</div>';
Output:
--------
var result = '<div>1</div><div>2</div><div>3</div><div>4</div>';

我希望这是在控制器中完成的,我已经尝试了以下操作:

var template = '<div ng-repeat="item in items">{{item.data}}</div>';
var linkFunction = $compile(template);
var result = linkFunction($scope);
console.log(result); // prints the template itself!

谢谢!

试试这个:

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

为此,我在几个项目前为自己制定了一个指令:

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

然后例如:

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

甚至字符串可以是动态的:

<div ng-repeat="item in items" ng-html-compile="item.template">
</div>