2013-02-22 49 views
2

是否可以使用AngularJs而不是页面呈现模板,但可能在内存中?我需要准备HTML作为电子邮件发送。 我想我可以渲染隐藏的div的东西,然后以某种方式分配给它的内容变量,但对我来说,它看起来丑陋:(AngularJs中的模板准备

回答

2

你可以看看$编译功能:http://docs.angularjs.org/api/ng $编译

例子:

function MyCtrl($scope, $compile){ 
    // You would probably fetch this email template by some service 
    var template = '</div>Hi {{name}}!</div></div>Here\'s your newsletter ...</div>'; // Email template 

    $scope.name = 'Alber'; 

    // this produces string '</div>Hi Alber!</div></div>Here\'s your newsletter ...</div>' 
    var compiledTemplate = $compile(template)($scope); 

}; 
+0

非常感谢!这正是我需要的。也许你也可以提示我如何从控制器中的文件加载模板? – Alber 2013-02-22 12:21:45

+0

@Alber简而言之,您将使用该服务(请参阅http://docs.angularjs.org/api/ng.$http)。您应该发布新的SO问题以获得指导。 – Stewie 2013-02-22 12:41:44

+0

@Alber ...如果你不介意接受答案,如果它回答你的问题。谢谢。 – Stewie 2013-02-22 16:10:36

0

当然,你可以使用$编译服务呈现模板渲染的模板将是不附加到DOM树中的DOM节点,你不必附加。它可以做到这样的事情:

<!doctype html> 
<html ng-app="myApp"> 
<head> 
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script> 
    <script type="text/javascript"> 
    var myApp = angular.module('myApp', []); 

    myApp.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile){ 
     var compiled; 
     $scope.compileTemplate = function() { 
      var template = '<ul><li ng-repeat="i in [1, 2, 3]">{{i}}</li></ul>'; 
      var linker = $compile(template); 
      compiled = linker($scope); 
     } 
     $scope.sendEmail = function() { 
      alert("Send: " + compiled[0].outerHTML); 
     } 
    }]); 
    </script> 
</head> 
<body ng-controller="MainCtrl"> 
    <button ng-click="compileTemplate()">Compile template</button> 
    <button ng-click="sendEmail()">Send email</button> 
</body> 
</html> 

我之所以将它们分成两个不同的功能是因为,当您编译并将其链接到范围时,直到下一个摘要之后才会填充数据。也就是说,如果您在compileTemplate()函数的末尾访问compiled[0].outerHTML,它将不会被填充(除非您使用超时...)。