我的应用程序中有以下 Controller :
主 Controller :
app.controller('AppCtrl', ['$scope', function ($scope) {
$scope.app = {
amount: 0
};
}]);
子 Controller :
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);
}]);
另一个子 Controller :
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 函数。你知道我该怎么做吗?
最佳答案
您的主 Controller :
app.controller('AppCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {
$scope.app = {
amount: timeOutService.amount
};
}]);
您可以拥有这样的通用服务
:
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);
}
});
并且在您的多个 Controller
中,您可以注入(inject)相同的内容:
子 Controller :
app.controller('ChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) { console.log("timeOutService", timeOutService);
timeOutService.timeLoop(20);
}]);
另一个子 Controller :
app.controller('AnotherChildCtrl', ['$scope','timeOutService', function ($scope,timeOutService) {
timeOutService.timeLoop(20);
}]);
下面是一个工作 fiddle : https://jsfiddle.net/40zodv7b/
关于angularjs - 更新服务内的范围值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356671/