Reputation: 1655
I have an impression that all data-related requests has to be delegated to services/factories. But reading examples of $http implementation met not once that they are put right inside of a controller, e.g.:
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
$http.get('data/posts.json').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
is that considered as normal practice/pattern or it is just for the sake of an example?
Upvotes: 1
Views: 203
Reputation: 146014
So best practices are dependent on the project-specific context, mostly overall code size of your application but also size of team, length of project/engagement, etc. For a small utility with just a few hundred lines of code, creating a service to encapsulate a single use of $http is over engineering. It makes your project harder, not easier, to read and maintain. However, for a full-size application with many modules, dozens of files, thousands of lines of code, where the same service logic might need to be reused across several controllers, then yes, it makes sense to move your $http
code to a service where it can be independently encapsulated, shared, and tested. So no, for "normal" applications (medium or large in size), using $http
in a controller is not considered a best practice pattern. However, for an instructive example/demo code snippet, or a very trivial project, it's fine.
Upvotes: 3