初始化多个控制器的$scope变量 – AngularJS

我有3个执行类似任务的控制器:

> PastController查询API以查找过去的系统中断.
> CurrentController查询API以查找当前系统中断
> FutureController查询API以确定将来的系统中断

它们各有特色(尽管它们具有相似的功能).但是,它们都是从定义相同的$scope变量开始的:

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

我可以使用服务或工厂在一个地方初始化这些变量而不是重复代码吗?

我没有测试代码,但如果你想使用服务,这是我的想法,希望它有效.

首先创建服务:

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!"
    };

  });

最后,您必须正确地将创建的服务注入控制器并从服务调用initialize函数

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

…并在每个控制器中设置.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...