1

我的 AngularJS 应用程序中有一个服务和一个控制器,它们应该在同一个模块中,但是是两个不同的文件:

// File 1 (Service)
angular.module('myService', ['ngRoute'])
.service('myService', // ... 


// File 2 (Controller)
angular.module('myController', ['ngRoute'])
.controller('myController', // ..

这工作正常。现在我想在一个模块中拥有服务和控制器,这样我就可以只加载一个而不是两个模块。所以我将第一行(两个文件的)更改为:

// Change in both files:
angular.module('myModule', ['ngRoute'])

但现在我得到一个错误:

错误:[$injector:unpr] ...

也许有人知道,这里可能出了什么问题。非常感谢!

4

2 回答 2

1

你有两个选择——

  1. 使用迈克尔提到的变量

或者

  1. 像使用它 -

// Initialize myService Module in any JS file 
   (make sure this file is included before File 1 and File 2
angular.module('myService', ['ngRoute']);

// File 1 (Service)
angular.module('myService').service('myService', // ... 

// File 2 (Controller)
angular.module('myService').controller('myController', // ..

于 2014-11-05T12:58:28.810 回答
1

您可以执行以下操作:

var myApp = angular.module('myApp', []);

myApp.controller("myService"

myApp.service("myApp")

或者

angular.module("myModule").controller

angular.module("myModule").service

如果您使用 angular.module('myService', []) 两次,您将两次初始化同一个模块。如果您只使用 angular.module("myModule"),而没有依赖项,那么您只是在调用它。

于 2014-11-05T11:56:33.017 回答