1

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?

2
  • 1
    As a good design pattern it is better to use $http in service/factories. Use $resourse rather than $http Commented Oct 29, 2014 at 6:22
  • 1
    where is just example how to use $http. But for coding most of people use every logical transaction, retirving etc in service. Controller should only as a messenger between view and service. Commented Oct 29, 2014 at 6:23

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.