模块间通信,角度Js,工厂

时间:2016-09-23 19:29:31

标签: javascript html angularjs

我有一个简单的应用程序,我正在Angular中开发。我尽可能地简化了下面的内容。我试图制作globally available library injectible(没什么特别的):

我的app.module.js文件的定义简单如下:

angular.module('dogApplication', [
    'dogModule',
    'dogSelection'
]);

index.html文件的定义如下(为便于阅读而去内脏):

<html lang="en" ng-app="dogApplication">
    <head>
        <!-- ... -->
        <script src="app/app.module.js"></script>
        <script src="app/dogs/dog.module.js"</script>
        <script src="app/dogs/dog.factory.js"</script>
        <script src="app/dogSelection.module.js"></script>
        <!-- controllers then imported -->
    </head>
    <body>
        <!-- content -->
    </body>
</html>

.module个文件定义了每个其他组件,控制器,工厂等附加到的模块,其中app.module.js是&#34; main&#34;模块附件。

dog.factory.js定义如下:

angular
    .module('dogModule')
    .factory('dog', function($window) {
        // do logic defined by James Hill in linked article
        return friendly;
    });

然后我有一个控制器:

angular
    .module('dogSelection')
    .controller('dogSelectionController', ['$scope', 'dog', function ($scope, dog) {
        if (dog)
        {
            console.log('it worked');
        }
    }])

访问该应用程序时,我收到一条糟糕的错误消息,我无法解决:

angular.js:13920 Error: [$injector:unpr] Unknown provider: dogProvider <- dog <- dogSelectionController
http://errors.angularjs.org/1.5.8/$injector/unpr?p0=dogProvider%20%3C-%20dog%20%3C-%20dogSelectionController
    at angular.js:68
    at angular.js:4511
    at Object.getService [as get] (angular.js:4664)
    at angular.js:4516
    at getService (angular.js:4664)
    at injectionArgs (angular.js:4688)
    at Object.invoke (angular.js:4710)
    at $controllerInit (angular.js:10354)
    at nodeLinkFn (angular.js:9263)
    at angular.js:9673

通过上述方式设置,为什么dog服务可通过DI dogSelectionController使用?

我知道.factory( //...方法中的代码可以正常工作,因为我可以将它附加到控制器定义的末尾;但是,我希望工厂可以在整个应用程序中使用。这可能吗?

2 个答案:

答案 0 :(得分:0)

第一个问题我看到你需要一个模块之后的数组。 即使没有模块依赖项。所以它是.module('dogSelection', [])而不是.module('dogSelection') - 我看到的下一个问题是你需要在注入之前定义模块狗使用的模块。如果没有一个模块来定义dob来自哪个狗将会像你看到的那样抛出一个错误。像这样的东西

模块:

angular.module('dogModule', [])

.factory('dog', function($window) 
{

});

控制器:

angular.module('dogSelection', [
  'dogModule'
])

.controller('dogSelectionController', ['$scope', 'dog', function ($scope, dog) 
{

}]);

答案 1 :(得分:0)

看起来'dogSelectionController'注射器应该从['$scope', 'leaflet'更改为['$scope', 'dog'。狗工厂未命名为'leaflet'

更新

作为共享工厂的解决方法是直接在主app模块上安装工厂。 我现在正在使用手机,所以目前无法给出更好的答案。

相关问题