Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 221
I_Debug_Everything Avatar asked Jan 26 '26 04:01

I_Debug_Everything


1 Answers

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.

like image 122
New Dev Avatar answered Jan 28 '26 16:01

New Dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!