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?
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.
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.
:: is used for one-time binding. The expression will stop recalculating once they are stable, i.e. after the first digest.
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.
$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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With