Compiling AngularJS Static Template

I have a template that I included in a view that fits into the $ templateCache template.

<script type="text/ng-template" id="ratesPopover"> <table class="rate-table"> <tr ng-repeat="rate in plan.rates"> <td>Rate</td> <td>{{rate}}</td> </tr> </table> </script> 

Then I have a directive in which I want to compile the template with the scope passed in, but I don't want the template to be required. I just want the $ compilation service to compile the template as a static HTML string, so I can add it to Twitter's Bootstrap Popover in the content-content attribute. No need for two-way binding.

 var template = angular.element('<div>' + $templateCache.get('ratesPopover') + '</div>'), popover = $compile(template)(scope); element.attr('data-content', popover.html()); 

What I see when displaying popover is a compiled template with no variables interpolated. Any ideas on what I can do wrong?

+4
source share
2 answers

Try entering the $interpolate module and then do

 var template = '<div>' + $templateCache.get('ratesPopover') + '</div>', popover = $interpolate(template)(scope); element.attr('data-content', popover); 
+3
source

This question is old, but my answer may help other people, I recently ran into this problem.

To interpolate the values ​​needed to complete the scope. apply:

 var template = angular.element('<div>' + $templateCache.get('ratesPopover') + '</div>'), popover = $compile(template)(scope); scope.$apply(function () { // popover is now interpolated }); 

If you are already in the $ digest loop, then calling $ apply will throw an error, in which case you just need to wait until the digest loop ends:

 var template = angular.element('<div>' + $templateCache.get('ratesPopover') + '</div>'), popover = $compile(template)(scope); $timeout(function () { // popover is now interpolated }); 
0
source

Source: https://habr.com/ru/post/1500207/


All Articles