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 this?
Here is my code :
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]; } })
Live Demo
The $window service refers to the browser window object. It is globally available in JavaScript, so it causes testability problems. In AngularJS, it is not globally available. It includes various methods like alert box, prompt box, confirms box, etc.
To inject window into a service with Angular, we can inject document into our service. Then we get window from document . to inject document with @Inject(DOCUMENT) private document: Document in the constructor signature. Then we get window from this.
The $window service is a wrapper around window object, so that it will be easy to override, remove or mocked for testing. It is recommended to use $window service in AngularJS instead of global window object directly. Want to check how much you know AngularJS 1?
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); })
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]; } })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With