I am trying to load a html template with ng-repeats in it and then use the $compile
service to compile it and use the compiled html in an email.
The problem.... Ok before asking let me set terminology...
binding placeholder: {{customer.name}}
binding value: 'john doe'
Using $interpolate
i get the actual binding values but does not work with ng-repeats.
Example:var html = $interpolate('<p>{{customer.name}}</p>')($scope)
Returns: '<p>john doe</p>'
Ng-repeats do not work
Using $compile
i get the bindings placeholders ie {{customer.name}}
but what I need is the binding value 'john doe'
.
Example: var html = $compile('<p>{{customer.name}}</p>')($scope
)
Returns: '<p>{{customer.name}}</p>'
Once I append to a page I see the binding values. But this is for email not for a page plus it has ng-repeats that $compile
can compile
How can I create a dynamic email template that after compiling it, it returns html with binding values and not just the binding placeholders so I can send it as email?
Using $compile is the right way to go. However, $compile(template)($scope)
doesn't yield the interpolated HTML that you expect right away. It just links the compiled template to a scope to be interpolated during the next $digest
. To get the desired HTML, you need to wait for that interpolation to happen, like so:
var factory = angular.element('<div></div>');
factory.html('<ul ng-repeat="...">...</ul>');
$compile(factory)($scope);
// get the interpolated HTML asynchronously after the interpolation happens
$timeout(function () {
html = factory.html();
// ... do whatever you need with the interpolated HTML
});
(working CodePen example: http://codepen.io/anon/pen/gxEfr?editors=101)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With