gpt4 book ai didi

javascript - 如何在 ng-repeat (AngularJS) 中绑定(bind)多个 JSON 文件?

转载 作者:行者123 更新时间:2023-11-29 10:13:50 25 4
gpt4 key购买 nike

我有多个 JSON 文件:

ma​​in.json:

{
"MainRegister": [
{
"name": "Name1",
"url": "url1.json",
},
{
"name": "Name2",
"url": "url2.json",
},
]
}

url1.json

{
"SubInformation": {
"description": "Hello World 1",
"identifier": "id1",
}
}

url2.json

{
"SubInformation": {
"description": "Hello World 2",
"identifier": "id2",
}
}

现在我想在我的 index.html 中创建一个 ng-repeat div,以便它加载文件中的所有字段,而且我想显示以下输出:

  • Name1:Hello World 1 (id1)
  • Name2:Hello World 2 (id2)

如何以 ng-repeat 方式绑定(bind)这些文件?或者还有其他方法吗?

最佳答案

您需要先加载它们,然后在数组中设置一个包含必要数据的范围变量。您可以在 Controller 中执行 $http get(如下例所示),但如果它是可重用的或不仅仅是一个简单的应用程序,我建议在注入(inject)服务中执行此操作。

.controller('MyCtrl', function($scope,$http){
$scope.entries = [];
$http.get('main.json').success(function(data) {
angular.forEach(data.MainRegister,function(entry) {
$http.get(entry.url).
success(function(data) {
$scope.entries.push(angular.extend(entry,data.SubInformation);
});
});
});
});

然后你的模板看起来像

<div ng-repeat="entry in entries">
<span>{{entry.name}}: {{entry.description}} ({{entry.id}})</span>
</div>

如果你想对它们进行排序,或者以特定顺序加载 $scope.entries,或者如果你不想在所有条目都准备好之前显示任何条目,则可以使用过滤器,然后你可以设置一个现成的变量,或者只在最后设置 $scope.entries,等等。

我补充一点,我不喜欢那种越来越深的嵌入式ajax调用,以及它们的系列,但这是一个风格问题。我已经成为 caolan 的异步库的忠实粉丝,因为它使上面的 Controller 代码更加清晰。 http://github.com/caolan/async

关于javascript - 如何在 ng-repeat (AngularJS) 中绑定(bind)多个 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27188281/

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