How to `inject` `$window` object to the `config` in AngularJS

后端 未结 2 1660
陌清茗
陌清茗 2020-12-29 02:37

I am trying to inject the $window object into the config method in AngularJS, but I keep getting an error...

What is the correct way to do

相关标签:
2条回答
  • 2020-12-29 03:23

    Only constants and providers can be injected in config block. $window is a service. & it might not be available or configured while execution of config block so angular prevents it from using it.

    You can use run block. This acts as a main method for your angular app. This is executed just right before application is instantiated. By the time run block is executed all the service will be finished configuring and are ready to be injected. So you can use $window as below,

    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];
       }
      })
    
    0 讨论(0)
  • 2020-12-29 03:29

    you can't inject $window service to the config as services are not initialized at config time yet. however, you can inject them providers and get an instance. in your case:

    angular.module('myApp', [])
    
     .config(function ($windowProvider) {
       var $window = $windowProvider.$get();
       console.log($window);
     })
    
    0 讨论(0)
提交回复
热议问题