javascript 从 AngularJS 模板字符串生成 HTML 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26386470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate HTML string from AngularJS template string
提问by fikry
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.
我有 angularjs 模板作为一个字符串,包括“ng-repeat”和其他指令。我想在控制器中编译它以将结果 HTML 生成为字符串。
Example on what I want to apply in Angular:
我想在 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>';
I want this to be done in the controller I've and I tried the following:
我希望这在控制器中完成,我尝试了以下操作:
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!
Thanks!
谢谢!
采纳答案by Fordio
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());
回答by Ali Habibzadeh
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>