在 Angularjs 中将服务与控制器分开

Separate service from controller in Angularjs

我想在我的 angularjs 应用程序中将服务与控制器分开,我是通过以下方式实现的:

app.js有:

var myApp = angular.module('myApp',['restangular','ui.router','myApp.controllers','myApp.services']);

controllers.js:

 angular.module('myApp.controllers',[]);

services.js:

angular.module('myApp.services',[]);

我有一个与controllers.js相关的控制器:

angular.module('myApp.controllers',[]).controller('ContactController', ContactController);

ContactController.$inject = [ '$scope', 'ContactService' ];
function ContactController($scope, ContactService) {
     console.log("here call ctrl contact");
     $scope.contacts = ContactService.getAll(); 
}

ContactController 调用定义在单独文件中的服务 ContactService: 联系服务.js

angular.module('myApp.services',[])

.factory('ContactService', function(Restangular){
    var Contacts = Restangular.all('contacts');

    return {
        getAll : function(){
            return Contacts.getList().$object;
        }
    };

});

问题是当我尝试调用此控制器时出现以下错误:

Error: [$injector:unpr] Unknown provider: ContactServiceProvider <- ContactService http://errors.angularjs.org/1.2.19/$injector/unpr?p0=ContactServiceProvider%20%3C-%20ContactService

我该如何解决?

更新: 这是我的应用程序的结构:

我在app.js:

.state('contacts', {
        url: '/contacts',
        templateUrl: 'templates/contacts.html',
        controller: 'ContactController'
    })  
    .state('todos', {
        url: '/todos',
        templateUrl: 'templates/todos.html',
        controller: 'TodoController'
    })

在 index.html 我导入了所有 js 文件:

一旦你用m初始化了一个模块,angular.module('myApp.controllers', [])再次你不应该使用第二个参数dependency([])

所以, 在你的控制器中,

 `angular.module('myApp.controllers',[])` should be `angular.module('myApp.controllers')`

所以,

angular
  .module('myApp.controllers')
  .controller('ContactController', ContactController);
ContactController.$inject = ['$scope', 'ContactService'];
function ContactController($scope, ContactService) {
  console.log('here call ctrl contact');
  $scope.contacts = ContactService.getAll();
}

这同样适用于你的service/factory,

angular.module('myApp.services')
.factory('ContactService', function(Restangular){
    var Contacts = Restangular.all('contacts');

    return {
        getAll : function(){
            return Contacts.getList().$object;
        }
    };

});

PS: index.html 看到你的js文件注入顺序后,我发现了主要问题。

您的文件脚本顺序错误。在 ContactController 中,您使用的是 contactService ,它之前没有定义。 因此,如下更改 index.html 中的脚本顺序。

<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/services/ContactService.js"></script>
<script src="js/services/TodoService.js"></script>
<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/ContactController.js"></script>
<script src="js/controllers/TodoController.js"></script>

尝试包括

angular.module('myApp.controllers',['myApp.services'])

而不是

 angular.module('myApp.controllers',[])

干杯

似乎已通过按如下方式重新排序我的 js 文件的导入来解决此问题:

app.js然后是文件服务,然后是控制器。