在 angular 中注入 $window,有什么用?

injection of $window in angular, what for?

$window 注入 Angular 有什么用?

例如,

var myController = function ($scope, $window) {

   // window is still available here
};
myController.$inject = ['$scope', '$window'];

主要用于Doc

中所述的可测试性目的

While window is globally available in JavaScript, it causes testability problems, because it is a global variable. In angular we always refer to it through the $window service, so it may be overridden, removed or mocked for testing.

众所周知的最佳做法是尽可能避免使用全局变量。因此,Angular 为您提供了一个有效的 'angular' 方式选项来获取代码中的 window 对象作为服务。具有该选项的测试非常有用。