2016-03-02 61 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); 
     } 
    } 
})(); 

希望有所幫助!