yodalr
yodalr

Reputation: 10892

How to detect when content has loaded?

I'm creating a print page for my site: http://vivule.ee/0/print

I want to initiate window.print() when the page has loaded. I have tried different approaches, but have been unsuccessful. I know it's possible, because I can listen for finished Ajax calls, but how's it done in Angular?

My info path: HTML->angular->php->mysql table->php->json->angular->HTML

Upvotes: 5

Views: 7227

Answers (2)

yodalr
yodalr

Reputation: 10892

OK, got this to work by using promises, $watch, $timeout and setTimeout

About promises: http://andyshora.com/promises-angularjs-explained-as-cartoon.html

About angular $watch: How do I use $scope.$watch and $scope.$apply in AngularJS?

You can see it working live here: http://vivule.ee/0/print

Here's the beast I ended up with (check comments in the code):

if($routeParams.print){

    //Set variable for $watch to listen
    $scope.game = null;

    //Start script only after angular has changed content in ng-view
    $scope.$on('$viewContentLoaded', function(){

        //Listen to $scope.game variable change
        $scope.$watch('game', function(newVal, oldVal){

            //Force angular not to fire script on load
            if(newVal != oldVal) {

                //Force script to run AFTER ng-repeat has rendered its things to the DOM
                $timeout(function(){

                    //And finally setTimout to wait for browser to render the custom fonts for print preview
                    setTimeout(function(){

                        //Print document
                        window.print();
                        //window.close();
                    }, 100);
                }, 0);
            }
        }, true);
    });
}

Upvotes: 2

Pramod Sharma
Pramod Sharma

Reputation: 376

When promise (Ajax) is resolved then you can set a flag

Like getApplication.then(function (response){ //do some stuff $scope.isApplicaionLoaded =true; });

and in UI you may use the flag like ng-show="isApplicaionLoaded"

Upvotes: 0

Related Questions