我想在angularjs應用程序內使用長輪詢。我有一個控制器中的長輪詢,它正在更新在視圖中引用的範圍變量。 當我逐句通過代碼時,發生了輪詢,並且正在返回期望的數據,但視圖永遠不會更新。AngularJS長輪詢查看未更新
longpolltest.js
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function($scope, $timeout) {
$scope.value = 1;
function poll() {
var d = new Date();
var n = d.getTime();
$scope.value++;
$.ajax({
type: 'GET',
url: '/gs/async?millis=' + n,
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
success: function(data) {
var obj = jQuery.parseJSON(data);
if (obj.type == 'ServerTime')
$scope.myTime = object.Data.Time;
setTimeout("poll()", 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus + " " + errorThrown);
setTimeout("poll()", 10000);
}
});
}
poll();
});
longpolltest.html
<!DOCTYPE html>
<html>
<head lang="en">
<!-- jQuery JavaScript -->
<script src="js/ext/jquery-1.12.0.min.js"></script>
<!-- angular library -->
<script src="js/ext/angular/angular.min.js"></script>
<script src="js/ext/angular/angular-route.min.js"></script>
<script src="js/longpolltest.js"></script>
<meta charset="UTF-8">
<title>Long poll test</title>
</head>
<body ng-app="myApp">
<div>
<div ng-controller="MyController">
<p>
Time: {{myTime}}
Poll#: {{value}}
</p>
</div>
</div>
</body>
爲什麼認爲不會得到更新將大大意識到任何想法。
在此先感謝。
你需要'$範圍。$適用()'只要你更新'$ scope.myTime'在AJAX功能 –
您沒有使用對於ajax請求,我還看到使用'setTimeout'(而不是'$ timeout' /'$ interval') - 摘要循環不會「知道」這些更改,因此視圖不會得到改變 –
你正在做角度範圍之外的兩件事情。第一個是jQuery的AJAX,第二個是setTimeout。沒有必要使用其中任何一種,使用角度'$ http'和'$ timeout'。問題是這些發生在angulars範圍之外,所以它不知道它需要更新綁定。你是否有機會將角度應用於基於jQuery的應用程序。 – ste2425