初始化$范围变量多个控制器 - AngularJS [英] Initialize $scope variables for multiple controllers - 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
他们是每一个独特的(尽管他们类似的功能)。但是,他们都首先定义相同 $范围
变量:
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 ---//
});
我可以使用服务或工厂初始化在一个地方这些变量,而不是重复code?
Can I use a service or factory to initialize those variables in one place rather than repeating the code?
推荐答案
我没有测试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.
这篇关于初始化$范围变量多个控制器 - AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!