2つのコントローラーと2つのサービスで、3秒ごとに1つのサービスが呼び出されるという単純な例を作成しようとしています。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()のコードはどこですか? –