利用 $scope.apply()
Utilising $scope.apply()
我有以下工作正常,从 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()
});
$scope.apply
不是你的问题,范围将在 $http
请求结束时自动消化 和 $interval
。某些操作会自动 "inform" Angular 范围可能已更改并触发摘要;仅当您正在编写 "non-Angular" 代码时,您才必须显式触发范围摘要,否则 Angular 不会注意到任何更改。
不,您的问题是您正在调用 getData()
,然后让 它的 return 值 (undefined
) 每次执行十秒。这显然是无稽之谈。您只想将 函数本身 传递给 $interval
:
$interval(getData, 10000);
// look ma, ^^^^^, no parentheses
我有以下工作正常,从 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()
});
$scope.apply
不是你的问题,范围将在 $http
请求结束时自动消化 和 $interval
。某些操作会自动 "inform" Angular 范围可能已更改并触发摘要;仅当您正在编写 "non-Angular" 代码时,您才必须显式触发范围摘要,否则 Angular 不会注意到任何更改。
不,您的问题是您正在调用 getData()
,然后让 它的 return 值 (undefined
) 每次执行十秒。这显然是无稽之谈。您只想将 函数本身 传递给 $interval
:
$interval(getData, 10000);
// look ma, ^^^^^, no parentheses