Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the window from Angular expression

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?

like image 391
tamacun Avatar asked Jan 08 '14 14:01

tamacun


People also ask

What are angular expressions?

AngularJS expressions can also be written inside a directive: ng-bind="expression" . AngularJS will resolve the expression, and return the result exactly where the expression is written. AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.

What is window in angular?

AngularJs includes $window service which refers to the browser window object. In the JavaScript, window is a global object which includes many built-in methods like alert(), prompt() etc. The $window service is a wrapper around window object, so that it will be easy to override, remove or mocked for testing.

What is :: In AngularJS?

:: is used for one-time binding. The expression will stop recalculating once they are stable, i.e. after the first digest.

What is the correct syntax to write an expression in angular?

Which of the following is the correct syntax for writing AngularJS expressions? The syntax for applying multiple filters in AngularJS is: {{expression | filter1 | filter2 | …}} 3.


1 Answers

$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'));
like image 151
Stewie Avatar answered Dec 01 '22 13:12

Stewie