我有以下工作正常,从RESTful api提要中提取信息
app.controller('servicesController', ['$scope', '$location', '$http', '$interval',
function($scope, $location, $http, $interval) {
var getData = function() {
// Initialize $scope using the value of the model attribute, e.g.,
$scope.url = "https://(remote link to JSON api)";
$http.get($scope.url).success(function(data) {
$scope.listOfServices = data.runningServices; // get data from json
});
};
getData();
$interval(getData(), 10000);
}
]);
但是我的视图没有按预期每10秒更新一次。我已经读过,我需要在上面的代码中使用$ scope.apply()。
我尝试放置以下内容(在上面的适当位置)
$http.get($scope.url).success(function(data) {
$scope.listOfServices = data.runningServices; // get data from json
$scope.apply(); //I also tried $scope.runningServices.apply()
});
答案 0 :(得分:1)
$scope.apply
不是您的问题,范围将在$http
请求和 $interval
结束时自动消化。某些操作会自动“通知”Angular范围可能已更改并触发摘要;只有当您编写“非Angular”代码时,您才必须明确触发范围摘要,否则Angular不会注意到任何更改。
不,您的问题是您正在呼叫getData()
,然后每隔十秒执行一次返回值(undefined
)。这显然是胡说八道。您只想将函数本身传递给$interval
:
$interval(getData, 10000);
// look ma, ^^^^^, no parentheses