如何在AngularJS中为`config`注入``window`对象

use*_*080 31 angularjs

我试图将$window对象注入configAngularJS中的方法,但我一直收到错误...

这样做的正确方法是什么?

这是我的代码:

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];
   }
})
Run Code Online (Sandbox Code Playgroud)

现场演示

小智 82

您无法将$window服务注入配置,因为服务尚未在配置时初始化.但是,您可以注入提供者并获取实例.在你的情况下:

angular.module('myApp', [])

 .config(function ($windowProvider) {
   var $window = $windowProvider.$get();
   console.log($window);
 })
Run Code Online (Sandbox Code Playgroud)


kis*_*nio 11

只能在配置块中注入常量和提供程序.是一项服务.并且在执行配置块时可能无法使用或配置,因此angular会阻止它使用它.$window

您可以使用运行块.这是角度应用程序的主要方法.这是在实例化应用程序之前执行的.到执行运行块时,所有服务都将完成配置并准备注入.所以你可以使用$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];
   }
  })
Run Code Online (Sandbox Code Playgroud)