【问题标题】:How render an AngularJS template held in a variable?如何渲染保存在变量中的 AngularJS 模板?
【发布时间】:2014-10-29 11:01:20
【问题描述】:

我有一个 AngularJS 模板作为字符串保存在变量中,例如:

var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';

作为参考,此字符串已从外部 API 返回(因此它保存在变量中,而不是物理文件中)。

如何使用 Angular 的模板引擎渲染这个模板,并正确绑定 {{ title }}{{ intro }} 等表达式?

【问题讨论】:

    标签: javascript angularjs templating


    【解决方案1】:

    这可能行得通,也许......

    var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';
    
    var myApp = angular.module('myApp', []);
    myApp.run(function($templateCache) {
      $templateCache.put('templateId.html', templateContent);
    });
    

    ....

    <div ng-include src=" 'templateId.html' "></div>
    

    .... 我可能在上面错误地使用了 ng-include,请参阅此处的文档:https://docs.angularjs.org/api/ng/directive/ngInclude

    更新 我很好奇,所以做了一个plunkr。这里

    http://plnkr.co/edit/xApbUzlCQkMXlI4zmFBm?p=preview

    它正在工作 =)

    <h4>first</h4>
    <div ng-include src=" 'cached.html' "></div>
    
    <br/>
    
    <h4>second</h4>
    <div ng-include=" 'cached.html' "></div>
    

    【讨论】:

      【解决方案2】:

      Compile and Link它与你的范围:

      var templateContent = '<h1>{{ title }}</h1><p>{{ intro }}</p>';
      $scope.title = 'test title';
      $scope.intro = 'test intro';
      
      var compiledAndLinked = $compile(templateContent)($scope);
      

      编辑:
      这是和示例:

      HTML:

      <div ng-app='app'>
          <div direct>
          </div>
      </div>
      

      JS:

        var app = angular.module('app',[]);
      
      app.directive('direct', function($compile){
        return {
            restrict: 'A',
            replace: 'true',
            template: '<div>\
                        <input type="text" ng-model="inputHtml" />\
                        <button ng-click="createHtmlInputText()">Create Sample Html</button>\
                        <br/>\
                        <button ng-click="generateHtml()">Generate Html And Append</button>\
                      </div>',
            link: function (scope, element, attrs) { 
                scope.title = 'test title'
                scope.generateHtml = function(){
                      var compiled = $compile('<br/>' + scope.inputHtml)(scope);
                      element.append(compiled);
                }
                scope.createHtmlInputText = function(){
                    scope.inputHtml = '<span style="color:red">{{title}}</span>';
                }
            } 
        };
      });
      

      JSFIDDLE

      【讨论】:

      • 谢谢 Amir - 您对如何将 compiledAndLinked 添加到 DOM/页面有什么建议?
      • 我现在才添加了一个示例(经过编辑)。对不起,我以前没有这样做 - 我没有时间..
      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 2016-06-06
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      相关资源
      最近更新 更多