繁体   English   中英

来自不同模块的角度注入

[英]Angular injection from different modules

我明白了,这个错误

错误:[ng:areq] http://errors.angularjs.org/1.4.7/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20undefined

当我尝试以下操作时

HTML

<div ng-app="angularmodule">
    <div ng-controller="mycontroller">
        <div class="mydirective"  </div>
    </div>

指示

angular
    .module('ui.module', [])
    .directive('mydirective', function () {

        //some directive stuff in here, restricted as ‘C’

            }
        };
    });

工厂

angular
    .module('dataLayerModule', [])
    .factory('datalayer', [$http],

        function (http) {

         //some method in here that uses http request
            return factory;
        });

控制器

angular
    .module(‘angularmodule’, [‘ui.module', 'dataLayerModule'])
     .controller('mycontroller', ['$scope', 'datalayer', function ($scope, datalayer) {

        //this is dependent on two modules being injected i.e. ‘ui.module','dataLayerModule'
    }]);

如果我从上面去掉工厂('dataLayerModule')模块注入,它就可以工作,例如

    angular
        .module('angularmodule’, ['ui.module'])
        .controller('mycontroller', ['$scope', function ($scope) {


        }]);

问题是我的“dataLayerModule”注入和它的“datalayer”工厂没有被注入,我想。 上面的 javascript 代码位于不同的文件中,但在 html 中正确加载。

我想做的是将工厂注入控制器,工厂将负责通过ajax获取json数据

这些不同模块的原因是“ui-module”来自我无法控制的第 3 方。

如果任何人都可以创建一个 plunker,这种注入只是正常运行/加载,我将不胜感激,这让我发疯

您在如何将$http依赖项注入工厂时存在语法错误,这很可能会破坏工厂代码。 您当前没有在注入依赖项的数组中包含工厂方法。 $http周围也没有引号,并且它没有被正确注入工厂(当它作为参数传递给函数时没有$符号)。 它应该是:

angular
.module('dataLayerModule', [])
.factory('datalayer', ['$http', function($http) {

    //some method in here that uses http request
    return factory;
}]);

替代语法

使用上面的语法(包括依赖项和数组中的函数),可能很难发现这些类型的错误。 另一种更明确的语法是将函数名称传递给工厂方法并进一步声明函数。

angular
    .module('dataLayerModule', [])
    .factory('datalayer', dataLayer);

dataLayer.$inject = ['$http'];

function dataLayer($http) {

    //some method in here that uses http request
    return factory;
}

在你的factory声明中,你说:

.factory('datalayer', [$http], function (http) {})

但我认为这就是你想要的:

.factory('datalayer', ['$http', function (http) {}])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM