我的应用程序中有以下控制器:
主控制器:
app.controller('AppCtrl', ['$scope', function ($scope) {
$scope.app = {
amount: 0
};
}]);
儿童控制器:
app.controller('ChildCtrl', ['$scope', function ($scope) {
var timeLoop = function (amount) {
$timeout(function () {
$scope.app.amount++;
if($scope.app.amount < amount) {
timeLoop(amount);
}
}, 10);
}
timeLoop(20);
}]);
另一名儿童控制员:
app.controller('AnotherChildCtrl', ['$scope', function ($scope) {
var timeLoop = function (amount) {
$timeout(function () {
$scope.app.amount++;
if($scope.app.amount < amount) {
timeLoop(amount);
}
}, 10);
}
timeLoop(100);
}]);
如何对服务做同样的事情?我不想在MainCtrl中使用timeLoop函数。你知道我怎么做吗?
答案 0 :(得分:2)
您的主控制器:
app.controller('AppCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {
$scope.app = {
amount: timeOutService.amount
};
}]);
你可以这样generic service
:
app.service('timeOutService', function($timeout) {
this.amount = 0;
this.timeLoop = function (amount) {
var that = this;
$timeout(function () {
that.amount++;
if(that.amount < amount) {
that.timeLoop(amount);
}
}, 10);
}
});
在你的multiple controllers
中,你可以注入相同的内容:
儿童控制器:
app.controller('ChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) { console.log("timeOutService", timeOutService);
timeOutService.timeLoop(20);
}]);
另一名儿童控制员:
app.controller('AnotherChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {
timeOutService.timeLoop(20);
}]);
下面是一个工作小提琴: https://jsfiddle.net/40zodv7b/