4

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

tshepang
  • 11,360
  • 21
  • 88
  • 132
yodalr
  • 8,066
  • 10
  • 31
  • 44

3 Answers3

3

You can use, $viewContentLoaded Emitted every time the ngView content is reloaded. Check this [link]: https://docs.angularjs.org/api/ngRoute/directive/ngView If you are loading ngView, this event you can use to make sure the view is fully loaded.

 $scope.$on('$viewContentLoaded', function(){
    $window.print();
  });
Ganesh
  • 934
  • 8
  • 12
  • not 100% reliable though as it can fire before all directives rendered – charlietfl Sep 06 '14 at 17:07
  • This fires when "ng-view" has loaded. I need to listen when content INSIDE ng-view has loaded. This right now only creates a print page without the actual content from mysql table. – yodalr Sep 07 '14 at 11:48
2

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);
    });
}
Community
  • 1
  • 1
yodalr
  • 8,066
  • 10
  • 31
  • 44
0

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"

Pramod Sharma
  • 326
  • 5
  • 13