更新服务内的范围值
Update scope value inside service
我的应用程序中有以下控制器:
主控制器:
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 函数。你知道我该怎么做吗?
您的主控制器:
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);
}]);
下面是工作 fiddle:
https://jsfiddle.net/40zodv7b/
我的应用程序中有以下控制器:
主控制器:
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 函数。你知道我该怎么做吗?
您的主控制器:
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);
}]);
下面是工作 fiddle: https://jsfiddle.net/40zodv7b/