如何在AngularJS中将$ window对象注入config中 [英] How to `inject` `$window` object to the `config` in AngularJS

查看:39
本文介绍了如何在AngularJS中将$ window对象注入config中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将$window对象注入AngularJS的config方法中,但是我一直遇到错误...

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

正确的方法是什么?

这是我的代码:

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

实时演示

推荐答案

您不能将$window服务注入到配置中,因为服务尚未在配置时初始化.但是,您可以向它们注入提供程序并获取实例.在您的情况下:

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

这篇关于如何在AngularJS中将$ window对象注入config中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆