是否可以从控制器调用工厂服务,它位于不同的js文件上(示例会很好),或者控制器和工厂服务必须在同一个文件上?
由于
答案 0 :(得分:1)
您可以在index.html中包含这两个脚本,然后在控制器中使用该服务:
的index.html
<script src="js/pictures/picture.service.js"></script>
<script src="js/pictures/controllers/pictures.js"></script>
这是服务picture.service.js:
(() => {
angular.module('gallery').factory('Picture', ['$http', 'Upload', function ($http, Upload) {
return {
all: () => {
return $http.get('/api/pictures');
},
findById: (id) => {
return $http.get(`/api/pictures/${id}`);
},
create: (picture) => {
return Upload.upload({
url: '/api/pictures/create',
data: picture
});
}
};
}]);
})();
这是我注入服务的控制器:
(() => {
angular.module('gallery').controller('Pictures', ['Picture', function (Picture) {
let pictures = this;
// You might want to use .then instead of .success (deprecated)
Picture.all().success((data) => {
pictures.pictures = data;
});
}]);
})();
这是一个带有简单MEAN堆栈项目的github repo示例。 https://github.com/NikolayKolibarov/MEAN-Simple-Gallery