简体   繁体   中英

$compile return html in object

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM