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
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];
}
})
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);
})