为多个控制器初始化 $scope 变量 - AngularJS [英] Initialize $scope variables for multiple controllers - AngularJS

查看:27
本文介绍了为多个控制器初始化 $scope 变量 - AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 3 controllers that do similar tasks:

  • PastController 查询 API 以了解过去的系统中断.
  • CurrentController 查询 API 以了解当前系统中断情况
  • FutureController 查询 API 以备将来系统中断使用
  • PastController queries an API for past system outages.
  • CurrentController queries an API for current system outages
  • FutureController queries an API for future system outages

它们都是独一无二的(尽管它们的功能相似).然而,它们都是从定义相同的 $scope 变量开始的:

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?

推荐答案

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

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

先创建服务:

    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.

这篇关于为多个控制器初始化 $scope 变量 - AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆