7

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

2
  • 1
    Maybe the problem with console.log is the same as stackoverflow.com/a/18597550/1529630 Commented Sep 3, 2013 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. Commented Sep 3, 2013 at 19:57

1 Answer 1

12

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.