Accessing the window from Angular expression

╄→гoц情女王★ 提交于 2019-12-10 14:59:10

问题


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:


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


来源:https://stackoverflow.com/questions/20998330/accessing-the-window-from-angular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!