3

I have 3 controllers that do similar tasks:

  • PastController queries an API for past system outages.
  • CurrentController queries an API for current system outages
  • FutureController queries an API for future system outages

They are each unique (despite their similar functions). However, they all begin by defining the same $scope variables:

app.controller("PastController", function ($scope) {
   $scope.Outages = "";
   $scope.loading = 0;
   $scope.nothing = 0;
   $scope.error = 0;
   //--- code continues ---//
});

app.controller("CurrentController", function ($scope) {
   $scope.Outages = "";
   $scope.loading = 0;
   $scope.nothing = 0;
   $scope.error = 0;
   //--- code continues ---//
});

app.controller("FutureController", function ($scope) {
   $scope.Outages = "";
   $scope.loading = 0;
   $scope.nothing = 0;
   $scope.error = 0;
   //--- code continues ---//
});

Can I use a service or factory to initialize those variables in one place rather than repeating the code?

arman1991
  • 1,166
  • 1
  • 18
  • 28
sqdge
  • 43
  • 3

1 Answers1

5

I didn't test the code, but this is my idea if you want to work with services, hope it works.

Create the service first:

    app.service('systemService', function(){

     // initialize object first
    this.info = {}; 
    this.initialize = function(){
      //  properties initialization
      this.info.Outages = "";
      this.info.loading = 0;
      this.info.nothing = 0;
      this.info.error = 0;

      return this.info;
    }

    this.fooFunction = function() {
        return "Hello!"
    };

  });

In the end, you have to inject the created service into controllers correctly and call the initialize function from service:

app.controller("PastController",['$scope','systemService', function ($scope, systemService) {
$scope.info = systemService.initialize();
$scope.fooFunction = systemService.fooFunction();
}]);

... and set so in each controller.

arman1991
  • 1,166
  • 1
  • 18
  • 28
  • 1
    Np, I'm glad that I could help :-) – arman1991 Nov 14 '14 at 19:42
  • 1
    @SidBhalke , sorry for late response. The idea is the same: just create another function in service and bind it to one $scope variable. I edited my answer, to see more details, here is a good post on this thema : [http://stackoverflow.com/a/16566144/4064237] – arman1991 Feb 22 '16 at 13:19