将模块注入控制器AngularJs

Inject module into controller AngularJs

本文关键字:AngularJs 控制器 注入 模块      更新时间:2023-09-26

我有两个AngularJs模块,一个是我的应用程序,另一个是常量列表。我想将常量模块注入到我的应用程序模块中,并使用控制器中的常量。我已经能够在工厂内实现这一点,但我无法访问控制器中的常量。

应用程序模块:

(function() {
    'use strict';
    angular.module('myapp', [
            'constants',
            'ngMaterial',
            'ngCordova',
            'ngStorage',
            'relativeDate',
            'ui.router',
            'myapp.services.myservice'
            ])

常量模块:

angular.module('constants', [])
.constant('appName', 'mynewapp');

在我的工厂里,我可以访问我的常量:

(function() {
    'use strict';
    angular.module('myapp.services.myservice', [])
        .factory('Myservice', function ($http, appName) {
           console.log(appName); //works great!

我无法访问常量的控制器

(function() {
    'use strict';
    angular.module('myapp')
        .controller('MyController', [
            '$cordovaOauth',
            '$state',
            '$rootScope',
            'Myservice',
            MyController
        ]);
    function MyController($cordovaOauth, $state, $rootScope, Myservice, appName ) {
            console.log(appName); //undefined

您忘记为appName常量声明依赖注入令牌:

.controller('MyController', [
    '$cordovaOauth',
    '$state',
    '$rootScope',
    'Myservice',
    'appName',  // <---- don't forget me
    MyController
]);