gpt4 book ai didi

javascript - ng-repeat 内的 $http 调用

转载 作者:行者123 更新时间:2023-12-03 03:54:18 24 4
gpt4 key购买 nike

我的 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 Controller :

// 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() 。谁能给点建议吗?

最佳答案

实际上@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>

关于javascript - ng-repeat 内的 $http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45024019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com