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

后端 未结 2 1662
陌清茗
陌清茗 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];
       }
      })
    

提交回复
热议问题