我的Web应用程序使用AngularJS通过$http
调用显示来自外部API的数据列表。数据通过函数调用在ng-repeat
内获取。
HTML:
// 'events' does not hold all data; call getData() to get the full data
<div ng-repeat="event in events">
{{getFullEventData(event.key)}}
{{full_event_data.name}}
{{full_event_data.information}}
</div>
AngularJS控制器:
// Fetch and store data in 'events' scope variable
$scope.events = ...
// Fetch and store data in 'full_event_data' scope variable,
// because 'events' does not have all the data for each event
var allEventData = [];
$http({
url: url,
method: "GET"
}).success(function(data, status, headers, config) {
allEventData = data;
}).error(function(data, status, headers, config) {
// ...
});
$scope.getFullEventData = function(key) {
for (var i = 0; i < allEventData.length; i++) {
var fetchedEvent = allEventData[i];
if (fetchedEvent.key === key) {
$scope.full_event_data = fetchedEvent;
}
}
}
但是,这不会在HTML中打印事件名称和信息(这些字段只是空白)。我怀疑在HTTP请求完成获取其他数据之前正在调用getFullEventData()
。有人可以建议吗?
答案 0 :(得分:1)
实际上@charlietfl是正确的,但答案可以用更多代码完成。 这个想法是获取额外的数据,然后将它们与现有数据合并。
// Fetch and store data in 'events' scope variable
$scope.events = ...
var additionalData;
// Fetch full event data
$http({
url: url,
method: "GET"
}).success(function(data, status, headers, config) {
// assign additional data into events
additionalData = data; // keep a copy of data for future use
assignData(data);
}).error(function(data, status, headers, config) {
// ...
});
function assignData() {
angular.forEach($scope.events, function(event) {
// find matching fetched event for each event in $scope.events
var fetchedEvent = additionalData.find(function(item) {
return event.key === item.key;
});
if (fetchedEvent) {
// additional info is merged into original object
angular.extend(event, fetchedEvent);
}
});
}
<div ng-repeat="event in events">
{{event.name}}
{{event.information}}
</div>
答案 1 :(得分:0)
你的功能没有多大意义。
你应该能够做到:
<div ng-repeat="event in data">
{{event.name}}
{{event.information}}
</div>
答案 2 :(得分:0)
IMO,您从$ http重新发送data
并不会通知角度触发更改检测。因此,当数据到达时,此时将不会触发getFullEventData()
。
您必须找到触发检测的方法。例如$scope.$apply
或$timeout
。