我是ANgularJS的新手,这是代码,我希望每次在数据库中更新数据时刷新表,但此代码在angularjs中不起作用。如何使用$ interval或AngularJS中的任何其他方式刷新表格
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http, $timeout) {
$http.get("http://localhost/students.php")
.then(function (response) {$scope.names = response.data.records;});
$timeout(callAtTimeout, 2000);
});
</script>
</body>
</html>
答案 0 :(得分:1)
这可以解决问题,但我不建议浪费资源。
$timeout(function(){
$http.get("http://localhost/students.php")
.then(function (response) {$scope.names = response.data.records;});
}, 2000);
答案 1 :(得分:1)
在你的控制器中试试这个
app.controller('customersCtrl', function($scope, $http, $timeout) {
function getData(){
$http.get("http://localhost/students.php")
.then(function (response) {
$scope.names = response.data.records;
setTimeout(function() {
getData();
}, 2000)
});
};
getData();
});
根据评论更新
请参阅此示例,它的工作正常,间隔为5秒,将代码与之比较
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script type="text/javascript">
angular.module("app",[])
.controller("ctrl",function($scope){
function getData(){
var time = new Date();
console.log('print at '+ time);
setTimeout(function() {
getData();
}, 5000)
};
getData();
});
</script>
</head>
<body ng-app="app" ng-controller="ctrl">
</body>
</html>
答案 2 :(得分:0)
应该是这样的
$http.get("http://localhost/students.php")
.then(function (response) {
$scope.$evalAsync(function () {
$scope.names = response.data.records;
});
});
});