Initialize $ scope variables for multiple controllers - AngularJS

I have 3 controllers that perform similar tasks:

  • PastController is requesting an API for past system crashes.
  • CurrentController requests an API for current system crashes.
  • FutureController is requesting an API for future system crashes.

They are 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 ---// }); 

Is it possible to use a service or factory to initialize these variables in one place, and not to repeat the code?

+3
angularjs angularjs-service angularjs-controller
source share
1 answer

I have not tested the code, but it is my idea, if you want to work with services, I hope this works.

First create a service:

  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 must correctly enter the created service in the controllers and call the initialization function from the service:

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

... and install it in each controller.

+4
source share

All Articles