如何将变量传递给AngularJs配置

时间:2015-10-27 16:24:24

标签: javascript angularjs

我与AngularJS Google Maps合作,需要在模块api_key部分配置config(问题类似于this one)。

我的问题是关于配置AngularJs模块

这是my test pen



var app = angular.module('myapp', [])
  /* 
     // HERE ????? 
     // I try to pass a value from the HTML (server side)

  .config(function($window){
    console.log($window.memKey);
  }) 

  */
  .controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
    $scope.name = $window.memName;
    $scope.city = $window.memCity;

    $scope.getMember = function(id) {
      console.log(id);
    };
  }]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
  var memKey = 'bb7de28f-0f89-4f14-8575-d494203acec7';
  var memName = 'John';
  var memCity = 'New-York';
</script>   

<div  ng-app="myapp" ng-controller="MainCtrl">
  Member name: {{name}} <br>
  Member city: {{city}}
</div>
&#13;
&#13;
&#13;

如何从HTML(服务器)端恢复memKey值?

2 个答案:

答案 0 :(得分:1)

根据您的声明,您的memKey处于可访问的范围内。

只是做

 app.config(function(){
    console.log(memKey);
  }) 

请参阅snippet

答案 1 :(得分:1)

如果您不使用注射阵列,则可以访问现有的角度模块。获得引用后,可以声明常量,例如:

<script type="text/javascript">
 var app = angular.module('myapp');  
 app.constant('memKey', 'bb7de28f-0f89-4f14-8575-d494203acec7');
 app.constant('memName', 'John');
 app.constant('memCity', 'New-York');
 //Or do them as one config object
</script>   

-

  .config(['memKey', 'memName','memCity'  function(memKey, memName, memCity) {
  }]);