加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 07:52:14 所属栏目:安全 来源:网络整理
导读:我有3个执行类似任务的控制器: PastController查询API以查找过去的系统中断. CurrentController查询API以查找当前系统中断 FutureController查询API以确定将来的系统中断 它们各有特色(尽管它们具有相似的功能).但是,它们都是从定义相同的$scope变量开始的
我有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();
}]);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读