我有一个包含 2 个模块、1 个 Controller (目前)和一项服务的应用程序。
我试过将模块和配置放在这样的文件中: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: '/'});
}
})();
然后像这样的 Controller :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);
}
}
})();
有人可以解释为什么它从不定义分离的 Controller 或服务,即使我在我的 index.html 中声明了两者吗?
最佳答案
您的 Controller 和服务声明以及函数名称不匹配(javascript 区分大小写),将服务声明为 Controller 并且您缺少依赖项。
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 中声明 Controller 和服务
关于javascript - 不同 .js 文档中的 ANGULAR 1.5 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38927089/