我有3个执行类似任务的控制器:
它们每个都是唯一的(尽管它们具有相似的功能)。但是,它们都从定义相同的$scope变量开始:
$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(); }]);
…并在每个控制器中进行设置。