如何在变量中保存AngularJS模板?

时间:2014-09-04 15:49:36

标签: javascript angularjs templating

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

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

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这可能有用,也许......

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

<强>更新 我好奇,所以做了一个傻瓜。这里

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>