如何将`$window`对象“注入”AngularJS中的`config`



我正试图将$window对象注入AngularJS中的config方法,但我一直收到一个错误。。。

正确的方法是什么?

这是我的代码:

angular.module('myApp', ['$window']) //is this wrong?
  .config(function ($window) { //this is not the way?
      console.log($window); //console.log fails //error
  })
  .controller("main", function($scope) {
    $scope.index = 0;
    $scope.num = number[$scope.index];
   $scope.increase = function () {
     $scope.index += 1;
     $scope.num = number[$scope.index];
   }
})

实时演示

您不能将$window服务注入配置,因为在配置时还没有初始化服务。但是,您可以为它们注入提供者并获得一个实例。在您的情况下:

angular.module('myApp', [])
 .config(function ($windowProvider) {
   var $window = $windowProvider.$get();
   console.log($window);
 })

只有常量和提供程序可以注入配置块$window服务&在执行配置块时,它可能不可用或不配置,因此angular阻止它使用它。

您可以使用运行块。这是你的angular应用程序的主要方法。这是在应用程序实例化之前执行的。当运行块被执行时,所有服务都将完成配置,并准备好注入。所以你可以使用$window如下,

angular.module('myApp', ['$window']) 
  .run(function ($window) { //use run rather than config
      console.log($window); 
  })
  .controller("main", function($scope) {
    $scope.index = 0;
    $scope.num = number[$scope.index];
   $scope.increase = function () {
     $scope.index += 1;
     $scope.num = number[$scope.index];
   }
  })

最新更新