我有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 ---// });
我可以使用服务或工厂在一个地方初始化这些变量而不是重复代码吗?
我没有测试代码,但如果你想使用服务,这是我的想法,希望它有效.
原文链接:https://www.f2er.com/angularjs/143383.html首先创建服务:
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(); }]);
…并在每个控制器中设置.