从 Angular 表达式访问窗口 [英] Accessing the window from Angular expression

查看:28
本文介绍了从 Angular 表达式访问窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 开发人员指南,我应该能够从 Angular 表达式内部访问浏览器窗口使用 $window.

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

与 JavaScript 的名称默认为全局窗口属性不同,Angular 表达式必须使用 $window 来引用全局窗口对象.例如,如果要调用定义在 window 上的 alert(),则必须在表达式中使用 $window.alert().

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().

但是我似乎无法从用 $scope.$eval 计算的表达式访问 $window.以下是我退出控制台时得到的一些输出:

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'

控制器具有 $window 作为依赖项.我可以从表达式访问范围变量和其他服务,但不能访问 $window,所以 $scope.$eval($window.alert()) 也不起作用.

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.

我在这里遗漏了什么?

推荐答案

$scope.$eval 根据 $scope 进行评估,因此您的评估只有在您将 $window 服务分配给作用域成员:

$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'));

这篇关于从 Angular 表达式访问窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆