Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
1  
Maybe the problem with console.log is the same as stackoverflow.com/a/18597550/1529630 –  Oriol Sep 3 '13 at 17:57
    
Thanks. Looks like it was the opposite of that problem. The correct output only showed up after the page was done loading, but not for the returnString. –  James Sep 3 '13 at 19:57

1 Answer 1

up vote 6 down vote accepted

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.