【问题标题】:Initialize $scope variables for multiple controllers - AngularJS为多个控制器初始化 $scope 变量 - AngularJS
【发布时间】:2015-01-11 07:37:50
【问题描述】:

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

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

【问题讨论】:

  • 这是实现控制器之间继承的完美示例。

标签: angularjs angularjs-service angularjs-controller


【解决方案1】:

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

先创建服务:

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

  });

最后,你必须将创建的服务正确地注入到控制器中,并从服务中调用初始化函数:

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

...并在每个控制器中进行设置。

【讨论】:

  • Np,我很高兴能帮上忙 :-)
  • @SidBhalke ,抱歉回复晚了。想法是一样的:只需在服务中创建另一个函数并将其绑定到一个 $scope 变量。我编辑了我的答案,以查看更多详细信息,这是关于这个主题的好帖子:[stackoverflow.com/a/16566144/4064237]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
相关资源
最近更新 更多