我在尝试对不同模块使用 Angular 依赖注入(inject)时遇到了一些问题。目前,我有以下内容。在我的 index.html
,文件按以下顺序加载(<body>
标记的末尾):
-
network.js
-
authentication.js
-
login.js
-
app.js
network.js
angular.module('services.network', [])
.factory('Network', ['$http', '$state', function ($http, $state) { ... }]);
authentication.js
angular.module('services.authentication', ['services.network'])
.factory('Authentication', ['$state', 'Network', function ($state, Network) { ... }]);
login.js
angular.module('controllers.login', [])
.controller('LoginCtrl', ['$scope', function ($scope) { ... }]);
app.js
var app = angular.module('parkmobi', [
'ngRoute',
'services.network',
'services.authentication',
'controllers.login'
]);
app.run(['$rootScope', function ($rootScope) {
$rootScope.$on('$viewContentLoaded', function () {
$(document).foundation('reflow');
});
}])
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
});
}]);
到此为止,一切似乎都很幸福。但是,现在我想使用 Authentication
服务于LoginCtrl
,我原以为是按如下方式完成的:
login.js
angular.module('controllers.login', ['services.authentication'])
.controller('LoginCtrl', ['$scope', 'Authentication', function ($scope, Authentication) { ... }]);
但是,这会导致以下注入(inject)错误:
Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=%24stateProvider%20%3C-%20%24state%20%3C-%20Authentication
R/<@http://localhost/testapp/vendor/angularjs/angular.min.js:6:417
最佳答案
出现错误是因为您在Authentication
工厂中注入(inject)了$state
提供程序,而app 中没有
ui.router
模块.jsparkmobi
模块。
它应该使用 $route
而不是 $state
因为你在 angular-router 中做你的路由。
angular.module('services.authentication', ['services.network'])
.factory('Authentication', ['$route', 'Network', function ($route, Network) { ... }]);
或者如果你想使用ui-router
,那么你需要在注册state
和ui时使用
模块应该包含在您的应用中。$stateProvider
。 router
关于javascript - 具有不同模块的 AngularJS DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30102420/