-1

In the Angular documentation for services, I came across this code:

angular.
 module('myServiceModule', []).
  controller('MyController', ['$scope','notify', function ($scope, notify) {
    $scope.callNotify = function(msg) {
      notify(msg);
    };
  }]).
 factory('notify', ['$window', function(win) {
    var msgs = [];
    return function(msg) {
      msgs.push(msg);
      if (msgs.length == 3) {
        win.alert(msgs.join("\n"));
        msgs = [];
      }
    };
  }]);

My question is, why not do it much simpler and just define the function notify inside the $scope.callNotify function?

If services are just functions defined elsewhere, aren't there much simpler ways of accomplishing the same thing?

CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

2 Answers2

1

Just think about resuing that code in another controller; you will not be able to do it.

But if you place it in a service, it can be injected and then reused everywhere.

richardtz
  • 4,993
  • 2
  • 27
  • 38
0

The primary reason is the idea is that there should not be any business logic present in the controller. It should just act as the glue between your scope and the model. Another reasons are code reusability, single responsibility principle, better testability, the list is endless.

Overall it is a good programming practice to break your app in smaller pieces which are easily testable on their own, which improves overall maintainability and testability of your app.

Abhishek Jain
  • 2,957
  • 23
  • 35