我有一个带有2个模块1控制器(现在)和一个服务的应用程序。
我试图将模块和配置放在这样的文件中:user.js
(function() {
'use strict';
var app = angular.module('Users', ['ngRoute']);
app.config(['$routeProvider', '$locationProvider', config]);
app.controller('usersController', [usersController, UsersService]);
app.service('UsersService', ['$http', UsersService]);
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/users', {
templateUrl: 'users/views/users-list.html',
controller: usersController
})
.otherwise({redirectTo: '/'});
}
})();
然后是一个像这样的控制器:userController.js
(function() {
'use strict';
var app = angular.module('Users');
app.controller('usersController', usersController);
/* @ngInject */
function usersController(UsersService) {
/*jshint validthis: true */
var vm = this;
vm.names = [
'Welder',
'Jéssica'
];
vm.findList = UsersService.findList()
.then(function(data) {
console.dir(data.data[0]);
vm.users = data.data;
console.log('vm: ', vm.users[0].name);
});
}
})();
最后我的服务:usersService
(function() {
'use strict';
var app = angular.module('Users');
app.controller('usersService', usersService);
function UsersService($http) {
var BASE_URL = 'http://localhost:3000/api/users';
this.create = create;
this.findList = findList;
this.find = find;
this.edit = edit;
this.remove = remove;
function create(user) {
var request = {
url: BASE_URL,
method: 'POST',
data: user
};
return $http(request);
}
function findList() {
var request = {
url: BASE_URL,
method: 'GET'
};
return $http(request);
}
function find(id) {
var request = {
url: BASE_URL + id,
method: 'GET',
};
return $http(request);
}
function edit(user,id) {
var request = {
url: BASE_URL + id,
method: 'PUT',
data: user
};
return $http(request);
}
function remove(id){
var request = {
url: BASE_URL + id,
method: 'DELETE'
};
return $http(request);
}
}
})();
有人可以解释为什么它永远不会定义分离的控制器或服务,即使我在index.html中声明了它们两者?
答案 0 :(得分:2)
您的控制器和服务声明以及函数名称不匹配(javascript区分大小写),将服务声明为控制器并且您缺少依赖项。
app.controller('usersService', usersService);
^ ^
function UsersService($http) {
^
应该是:
app.controller('usersController', ['usersService', usersController]);
/* @ngInject */
function usersController(UsersService) {
和
app.service('usersService', ['$http', UsersService]);
function UsersService($http) {
另外,不要在users.js
中声明控制器和服务