草庐IT

javascript - 是否可以将 Angular 模板编译为最终的 html 字符串?

coder 2023-08-09 原文

是否可以编译此 html 模板字符串:

"<p>List of products from {{supplier.name}}</p>
<p ng-repeat="ref in refs">{{ref}}</p>"

直接到 html 字符串,如:

"<p>List of products from Some Supplier</p>
<p>a0120</p>
<p>a0241</p>
<p>z1242</p>
<p>z3412</p>"

或者至少是不太干净的版本:

"<p class="ng-scope ng-binding">List of product from Duval</p>
<!-- ngRepeat: ref in refs track by $index -->
<p ng-repeat="ref in refs track by $index" class="ng-scope ng-binding">a0120</p>
<p ng-repeat="ref in refs track by $index" class="ng-scope ng-binding">a0241</p>
<p ng-repeat="ref in refs track by $index" class="ng-scope ng-binding">z1242</p>
<p ng-repeat="ref in refs track by $index" class="ng-scope ng-binding">z3412</p>"

我尝试使用 $compile(templateStr)($scope) 但返回的 dom 元素没有完全处理。 但是我设法没有使用以下指令将它编译为页面元素并检查该元素我可以看到它具有我正在寻找的最终 html:

app.directive('compile', function($compile) {
    return{
        restrict: 'A',
        scope: {
            compile: '=compile',
            data: '=ngData'
        },
        link: function(scope, element, attrs) {
            scope.$watch('data',
                    function(value) {
                        for (var k in scope.data)
                            scope[k] = scope.data[k];
                    }
            )

            scope.$watch('compile',
                    function(value) {
                        element.html(value);
                        var a = $compile(element.contents())(scope);
                    }
            )
        }
    }
})

有什么方法可以直接从模板中获取最终的 html 吗? 谢谢

附言: 我在这里想要实现的是直接在 CKEditor 中编辑模板(在文本模式下,而不是源代码) 并且最终只会进入源代码模式以添加一些“ng-repeat”属性。 使用像 Handlebars 这样的模板引擎需要 html 元素之外的占位符,并且会被 CKEditor 自动删除,因为它只处理 html。

可能的解决方案(hacky): 一种可能的方法是在隐藏元素上使用编译指令,并在 Controller 上加载 View 后读取元素的内容:

$scope.$on('$viewContentLoaded', $scope.onLoaded);
$timeout(function() {
    var el =$("#text div")[0]
    cleanAngularStuff(el)
    $scope.currMailTemplate.processed = el.innerHTML
});

cleanAngularStuff 函数只是为了清理额外的 Angular Directive(指令)和类。

我会发布 here如果有人想使用它或改进它。

在不向页面添加元素的情况下有更好的方法吗?

最佳答案

您需要做的是在 $digest 循环后访问已编译的元素。

所以在 $digest 循环中你可以做:

templateString = '<some-template-code/>';
...
var compiled = $compile(templateString)(scope);
// scope.$digest // only call this if not within a $digest cycle

// you can do a $timeout to let the previous digest cycle complete
$timeout(function(){
  var theHtml = compiled[0].outerHTML;
  console.log('the html with the variables', theHtml);
});

如果您还没有进入摘要循环,那么您需要手动调用 scope.$digest()。您可以在下面看到嵌入的示例。

(function(){
  "use strict";
  var app = angular.module('soApp', []);
  
  app.directive('showCompiledTemplate',[
            '$compile','$timeout',
    function($compile , $timeout) {
      return {
        restrict: 'E',
        template: '<div class="compiled-template">' +
			        '<div><textarea cols="40" rows="15" readonly></textarea></div>' +
          			'<div class="output"></div>' +
                  '</div>',
        scope: {
          data: '=',
          template: '='
        },
        link: function(scope,elem,attrs) {
            var textarea = elem.find('textarea')[0];
            var output = elem.children().children().eq(1);
			var updateOutput = function(tpl) {
                var compiled = $compile(tpl)(scope);
                $timeout(function(){
                    var theHtml = compiled[0].outerHTML;
                    textarea.value = theHtml;
                    output.html(theHtml);
                });
            };
            scope.$watch("template",function(tpl){
				updateOutput(tpl);
            });
            scope.$watch("data",function(){
                updateOutput(scope.template);
            },true);
        }
      };
    }
  ]);
  
  app.controller('MainCtrl', function() {
    this.data = {
      name: 'John',
      list: ['one duck','two ducks','three ducks']
    };
    //this.template = "<div>hi</div>";
    var template = '';
    template += '<div>\n';
    template += '  <p>{{data.name}}</p>\n';
    template += '  <ul>\n';
    template += '    <li ng-repeat="item in data.list">{{item}}</li>\n';
    template += '  </ul>\n';
    template += '</div>\n';
    this.template = template;
  });
  
 })();
.form-field {
    padding-bottom: 10px;
}
.form-field span {
    width: 70px;
    display: inline-block;
}
.compiled-template {
   display: -webkit-flex;
   display: flex;
   -webkit-flex-direction: row;
   flex-direction: row;
}
.compiled-template textarea {
    background-color: #eee;
    margin-right: 10px;
}
.compiled-template .output {
    border: 1px solid #ccc;
    padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<div ng-app="soApp">
  <div ng-controller="MainCtrl as main">
      <div class="form-field">
          <span class="form-label">Name:</span>
          <input type="text" ng-model="main.data.name" /> <br/>
      </div>
      <div class="form-field">
          <span class="form-label">Template:</span>
          <textarea ng-model="main.template" cols="40" rows="8"></textarea> <br/>
      </div>
      <div>
          <show-compiled-template data="main.data" template="main.template" />
      <div>
  </div>
</div>

关于javascript - 是否可以将 Angular 模板编译为最终的 html 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19402026/

有关javascript - 是否可以将 Angular 模板编译为最终的 html 字符串?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  5. ruby-on-rails - unicode 字符串的长度 - 2

    在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)

  6. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  7. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  8. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  9. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  10. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

随机推荐