我想将变量传递到该模板中,让它呈现,然后以字符串形式获取生成的 HTML。
我怎样才能在 AngularJS 中做到这一点?有没有类似render_to_string()
的功能function in Django ?
问题是我有一个 email.html
模板(你知道,布局电子邮件很痛苦),我想用变量填充它。
假设 email.html
的内容是这样的:
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Hello {{ name }}</h1>
<div>We will contact you soon in this email address: {{ email }}</div>
</body>
</html>
我有一个对象:data = {name: 'Foo', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5950507f5d5e4d115c5052" rel="noreferrer noopener nofollow">[email protected]</a>' }
然后我会期望类似于:
let messageBodyHtml = render('path_to_email.html', data)
最后,messageBodyHtml
将包含一个具有以下内容的字符串:
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Hello Foo</h1>
<div>We will contact you soon in this email address: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4a43436c4e4d5e024f4341" rel="noreferrer noopener nofollow">[email protected]</a></div>
</body>
</html>
最佳答案
您可以尝试以编程方式编译 HTML
。首先,从模板中删除 html
、head
和 body
标记,您不需要它们。
email.html
<h1>Hello {{ name }}</h1>
<div>We will contact you soon in this email address: {{ email }}</div>
使用服务$compile
来编译您的模板。
angular.controller('someController', ['$scope', '$compile', function($scope, $compile){
var templateString = '<div ng-include="\'./email.html\'" ></div>';
var newElem = angular.element(templateString);
$compile(newElem)($scope); // or use $scope.$new()
// use $timeout to wait until the $digest end and template is fetched/compiled
$timeout(function(){
// use .html() to get the final HTML
console.log(newElem.html());
});
}]);
使用 ngInclude
获取模板,使用 angular.element
、$compile
使用模板创建 element
使用 $timeout
等待结束,然后使用 newElem.html()
。
将此代码放入函数或指令中。
希望对你有帮助
关于javascript - 如何将 AngularJS 模板转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47472979/