我正在嘗試創建一個2控制器和2個服務的簡單示例,其中每3秒調用一個服務。無法綁定setInterval操作的值
控制器1調用服務,該服務更改控制器2中使用的值。我通過另一個服務傳遞值,但只有在按下示例中的「停止」按鈕(在波紋管中)後,該值纔會在我的html頁面上更新。
我可以更新每次投票的頁面值嗎?
<html ng-app="myApp">
<head>
<title>MyApp</title>
<script src="angular.js"></script>
<script>
var app = angular.module('myApp',[]);
app.service('SimpleService', function() {
var _value = 0;
var setValue = function(v) {
_value = v;
}
var getValue = function(){
return _value;
}
return {
setValue: setValue,
getValue: getValue
};
})
app.service('PollService', function(SimpleService) {
var poll = undefined;
var startPolling = function(){
poll = setInterval(function(){
console.info('poll...');
console.info(SimpleService.getValue());
SimpleService.setValue(SimpleService.getValue()+1);
}, 3000);
}
var stopPolling = function(){
clearInterval(poll);
}
return {
startPolling: startPolling,
stopPolling: stopPolling
};
})
app.controller('Controller1',function($scope, PollService){
var poll = undefined;
$scope.startPolling = function(){
PollService.startPolling();
}
$scope.stopPolling = function(){
console.info('stop');
PollService.stopPolling();
}
});
app.controller('Controller2', function($scope, SimpleService){
$scope.newVal = function(){
return SimpleService.getValue();
}
});
</script>
</head>
<body>
<div ng-controller="Controller1">
<button ng-click="startPolling()">Start</button>
<button ng-click="stopPolling()">Stop</button>
<br/>
<br/>
</div>
<div ng-controller="Controller2">
<h5>New value: {{newVal()}}</h5>
</div>
</body>
問候。
https://docs.angularjs.org/api/ng/service/$interval – sh0ber
與[本問題](http:// stackoverflow。com/questions/42701048/how-to-pass-vm-to-a-settimout-in-angularjs)在這裏應用。在這種情況下使用[$ interval](docs.angularjs.org/api/ng/service/$interval)作爲@ sh0ber提到 – lealceldeiro
PollService.stopPolling()的代碼在哪裏? –