1

I have some troubles whith print function in AngularJS. I have a button wich call au print function in my controller. But I have just that error :

TypeError: $window.print is not a function

HTML :

<md-button class="md-raised" ng-click="printThis()">Imprimer</md-button>

JS :

$scope.printThis = function(){
    console.info("Let go print !");
    alert("PLOP");
    window.alert("FOO");
    $window.alert("BAR");
    $window.print();
};

When I click on button, I have 3 alerts then the TypeError ! I tried both window.print() and $window.print() but nothing works... I really don't understand ! If i press ctrl + P, the chrome popup to print appears normally...

Need help please

0

2 Answers 2

0

your controller needs to inject the $window dependency,

.controller("YourController", function($window, $scope) {
   $scope.printThis = function(){
      $window.alert("BAR");
  };
}

If that doesn't work, I suggest you to remove any html element with an id of "alert" or "print".

If you have html element with id "print", it will overwrite window.print variable.

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

4 Comments

Sounds like he is already doing that... otherwise he would get the error on the line with $window.alert(...).
Like it ! I will search for "print" id or element or attribute in HTML ;-)
The problem comes from my module declaration. I set var print = angular.module('PrintModule', ['PrintServices']);, I rename in var printModule = ... and problem solved :-)
you can use function scopes so you won't do this in the future: (function(){ ...your code here...})(); that won't expose any variables to global scope.
0

Angular limits the access to the window object (or any other global variable).

To access $window you have to first inject it into the controller

angular.module('App', []).controller('Cnt', function($scope, $window) {
  $scope.print = function() {
    $window.print();
  }
});

Small demonstration: http://plnkr.co/edit/E0oCSuE3xceHp1Jtjh7g?p=preview

2 Comments

Sounds like he is already doing that... otherwise he would get the error on the line with $window.alert(...).
Absolutely, I inject $window in my controller. I think I have a conflict problem, when I do a console.debug($window), I see all properties but not print function ! Research in progress...

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.