1

so im calling a html template and want to bind the data with angular, so i get the data to bind, i get the html, when i try to compile it will return all the html binded but in (i think) object, what can i do to make it html.

This is the code

$.get("file.html", function(partial){

        var scope = $rootScope.$new();
        scope.data = result;

        var el = angular.element(partial);

        var compiled = $compile(el)(scope);
        var finalHtml = el[0];


        $timeout(function(){
            var calendar = window.open();
            calendar.document.write(finalHtml);
            calendar.focus();
            calendar.print();
        });
    });

I already try .html .toString String() nothing worked

Thank you in Advance

3
  • 2
    Why are you using jQuery to load a template? Use angular methods if you want to use angular. Where is this code from? $compile is only ever needed in own directives. Commented Sep 24, 2015 at 13:39
  • Use $templateRequester Commented Sep 24, 2015 at 13:40
  • @ Kevin Dreßler thank you for your reply, the result is just html but behave like object Commented Sep 24, 2015 at 13:40

1 Answer 1

4

Your compiled variable is an angular jQuery or jqlite element that can be inserted into your document. If you want to get the html for it, you can use use the outerHTML attribute on the underlying node (you get the underlying node by grabbing the first array element compiled[0]) - https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

var compiled = $compile(el)(scope);
// scope.$digest() // only call if not within an angular $digest already
$timeout(function() {
  var finalHtml = compiled[0].outerHTML;
  ...
}

According to the documentation "After linking the view is not updated until after a call to $digest which typically is done by Angular automatically." so you either have to manually call scope.$digest() or actually use one the angular API to do the request using either $http or preferably using $templateRequest like @ThinkingMedia suggested. After the angular $digest has run, then you can access the updated view.

I created a plunker here that shows how it all works properly using just the AngularJS api: http://plnkr.co/edit/rFcfgB3FWhsfyySfr0rU?p=preview

I also changed how the popup is opened a bit to deal with the security implication of doing popups.

Sign up to request clarification or add additional context in comments.

1 Comment

@JoãoReis I updated my answer to correct my mistake, use ThinkingMedia's suggestion, and provide a working example

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.