javascript - 如何将 AngularJS 模板转换为字符串?

标签 javascript angularjs django render

我想将变量传递到该模板中,让它呈现,然后以字符串形式获取生成的 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。首先,从模板中删除 htmlheadbody 标记,您不需要它们。

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/

相关文章:

javascript - RequireJS/AMD 外部模块解析

javascript - 优化圆弧以绘制仅在 Canvas 上可见的扇区

javascript - 无法绑定(bind)窗口方法: "Invalid calling object"

javascript - 控制台中的 Angular : get the scope I created (not the whole scope)

angularjs - web api身份验证后将 token 存储在浏览器本地存储中是否安全

python - Django 管理员 : removing app name from URL for single-app projects

javascript - 如何确定 iOS 上 Safari 崩溃的原因?

javascript - Angular slider 不显示

python - 由于启用了 django-social-auth 后端,无法登录到 django 管理页面

python - 我们如何使用带有 Selenium 的 Django LiveServerTestCase 来测试 https url