2

Is it possible to render template with AngularJs not on Page, but probably in memory? I need to prepare html to be send as email. I guess i could render something in hidden div, then in some way assign it content to variable , but for me it looks ugly :(

2 Answers 2

2

You can take a look at $compile function: http://docs.angularjs.org/api/ng.$compile

Example:

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); }; 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot! This is exactly i need. May be you could also prompt me how i could load template from file in controller?
@Alber In short, you would use a service for that (see docs.angularjs.org/api/ng.$http). You should probably post new SO question for guidance.
@Alber ...and if you don't mind accepting the answer if it answers your question. Thanks.
0

Sure, you can use the $compile service to render a template. The rendered template will be a DOM node that isn't attached to the DOM tree. And you don't have to attach it to get its content. You could do something like this:

<!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> 

The reason that I've divided them into two different functions here is because when you compile and link it to the scope, the template isn't filled with data until after the next digest. That is, if you access compiled[0].outerHTML at the end of the compileTemplate() function, it won't be filled (unless you use a timeout...).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.