Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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

like image 597
user2024080 Avatar asked Jun 21 '15 06:06

user2024080


People also ask

What is$ window in Angular js?

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.

How do you inject a window into a service?

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.

Why using$ window service preferred over traditional JavaScript window global variable?

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?


2 Answers

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);  }) 
like image 73
mkeremguc Avatar answered Sep 16 '22 13:09

mkeremguc


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];    }   }) 
like image 25
kishanio Avatar answered Sep 20 '22 13:09

kishanio