2016-03-02 34 views
0

我有以下的Angular模块。我如何从我的控制器中调用示例APIHost?调用模块常量?

angular.module('configuration', []) 
    .constant('APIHost','http://api.com') 
    .constant('HostUrl','http://example.com') 
    .constant('SolutionName', 'MySite'); 

回答

1

常数不过是一种提供者配方。

您需要在controller工厂函数中注入constant依赖关系,就是这样。

app.controller('testCtrl', function($scope, APIHost){ 
    console.log(APIHost) 
}) 

确保您configuration模块已被添加到主模块依赖 获得使用constant的提供商像下面

var app = angular.module('app', ['configuration', 'otherdependency']); 
app.controller(...) //here you can have configuration constant available 
1

像这样,就像任何服务或工厂一样。

我还包括从john papa's coding guidelines行业标准(种)的结构。

(function() { 
    'use strict'; 

    angular 
     .module('configuration') 
     .controller('ctrlXYZ', ctrlXYZ); 
    //Just inject as you would inject a service or factory 
    ctrlXYZ.$inject = ['APIHost']; 

    /* @ngInject */ 
    function ctrlXYZ(APIHost) { 
     var vm = this; 

     activate(); 

     function activate() { 
      //Go crazy with APIHost 
      console.log(APIHost); 
     } 
    } 
})(); 

希望有所帮助!