I_Debug_Everything
I_Debug_Everything

Reputation: 3816

Separating business logic from controller in AngularJS

I've come across many articles that shows how to separate business logic from controller and keep them in separate layers. As for angular, we add all the logic in our services,factories etc.

But I've come across the following line of code

angular.module('myApp').controller(function($scope,$userService) {    
  $scope.users = $userService.get('/users');    
  $scope.add = function() {
    // do something
  };    
});

and people still argue that we are still adding logic in our controllers. If that's true, then what will be the best way to initialize data in my controller so that I can avoid having logic in my controllers OR any best practices that can help me achieve those.

P.S I'm requesting suggestions strictly for Angular.

Upvotes: 3

Views: 3123

Answers (2)

Bradley Braithwaite
Bradley Braithwaite

Reputation: 1122

In the code example given, you could make use of a resource (https://docs.angularjs.org/api/ngResource/service/$resource) to abstract the URL detail. The code might then look as follows:

angular.module('myApp').controller(function($scope,Users) {    
  $scope.users = Users.query();    
  $scope.add = function() {
    // do something
  };    
});

I'm assuming that the the add function is linked to an ng-click event with the template, in which case that looks ok. If in place of // do something there was a a lot of code, that could perhaps be moved into a Service.

Taken from the AngularJS Docs:

Controllers are "classes" or "constructor functions" that are responsible for providing the application behavior that supports the declarative markup in the template.

As a rule of thumb, if it's not application behavior e.g. updating the model, handling a click event etc then abstract into a service.

Upvotes: 2

New Dev
New Dev

Reputation: 49590

There is definitely "logic" in a controller, but the logic should be limited to defining the ViewModel and changing it by reacting to events from the View and from the Model.

The logic deals with the state of the app, or a portion of the app's view for which the controller is authoritative for.

The logic that should not be in the controller has to do with backend knowledge, manipulation of the model's data, manipulation of the View / DOM, business logic that doesn't directly relates to how the data is staged for presentation.

Your example is fine, except for the "/users" part, which could benefit from being abstracted away in the service.

Upvotes: 2

Related Questions