Accessing the window from Angular expression

7.5k views Asked by At

According to the developer guide I should be able to access the browser window from inside Angular expressions with $window.

Unlike JavaScript, where names default to global window properties, Angular expressions have to use $window to refer to the global window object. For example, if you want to call alert(), which is defined on window, in an expression you must use $window.alert().

However I can't seem to access $window from expressions evaluated with $scope.$eval. Here are some outputs I get when logging out to the console:

console.log($window);                   // the Window object as expected
console.log($scope.$eval('$window'));   // undefined
console.log($scope.$eval('1+1'));       // 2
console.log($scope.$eval('scopeVar'));  // 'abc'

The controller has $window as a dependency. I can access scope variables and other services from expressions but not $window, so $scope.$eval($window.alert()) doesn't work either.

What am I missing here?

1

There are 1 answers

2
Stewie On BEST ANSWER

$scope.$eval evaluates against the $scope, so your evaluation will work only if you assign $window service to scope member:

$scope.$window = $window;  
console.log($scope.$eval('$window'));