Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Compiled HTML from AngularJS

I'm having trouble getting the compiled html of a page in AngularJS. Here's the code:

JS:

    <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script>
    <script>
        var app = angular.module('main', []);

        app.directive("compile", ['$compile', function ($compile) {
            return {
                link: function(scope, elem, attr){
                    var compiledHTML = $compile(elem.contents())(scope);
                    console.log(compiledHTML);
                    var returnString = '';
                    for(i=0; i<compiledHTML.length; i++)
                        returnString += compiledHTML[i].outerHTML;

                    console.log(returnString);
                }
            };
        }]);
    </script>

HTML:

<html ng-app="main" compile>
    <body>
        {{3 + 4}}
    </body>
</html>

What is strange is in the first console.log(), it shows the compiled data, 7, in the outerHTML property, but when I output all the .outerHTML, it shows the uncompiled version, {{3 + 4}}

like image 618
James Avatar asked Sep 03 '13 17:09

James


People also ask

How can you integrate AngularJS with HTML?

AngularJS extends HTML with ng-directives. The ng-app directive defines an AngularJS application. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data. The ng-bind directive binds application data to the HTML view.

How AngularJS is compiled?

AngularJS compilation process takes place in the Web Browser. No Server side or pre-compilation step is involved. Angular uses $compiler service to compile your Angular HTML page. The Angular compilation process begins after your HTML page (static DOM) is fully loaded.

What is compile and link in AngularJS?

Compile function: It is used for template DOM Manipulation and collect all of the directives. Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.


1 Answers

Looks like it was a timing issue. Waiting to process the compiledHTML did the trick.

$timeout(function(){
    var returnString = '';
    for(i=0; i<compiledHTML.length; i++)
        returnString += compiledHTML[i].outerHTML;

    console.log(returnString);
},0);
like image 148
James Avatar answered Oct 19 '22 07:10

James