Search code examples
angularjsangularjs-scope

Exception when exposing $window.print on angular scope


I'm exposing $window.print() on scope like so:

$scope.print = $window.print;

However, this results in an exception:

angular.js:13642 Exception message: Illegal invocation

I need to call print thru a separate function, like so to make it work:

$scope.print = printFn;
function printFn() { $window.print(); }

Any ideas why I can't use the first alternative? Running Angular 1.5.5


Solution

  • It is safe to assume that every object method depends on this unless proven otherwise, so method should be bound to its context before it is assigned as another object's method.

    window.print is native method, in Chrome it just throws Illegal invocation instead of complaining on inappropriate this context.

    Instead of wrapper function, it may be

    $scope.print = $window.print.bind($window);
    

    or

    $scope.print = angular.bind($window, $window.print);