调用模块常量?

时间:2016-03-02 16:11:20

标签: javascript angularjs

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

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

2 个答案:

答案 0 :(得分: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);
        }
    }
})();

希望有所帮助!

答案 1 :(得分:1)

常数只不过是一种提供者食谱。

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

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
相关问题