我有多个JSON文件:
I have multiple JSON files:
main.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重复DIV这样它加载从文件中的所有领域,而且我想要显示的输出如下:
Now I want to create a ng-repeat div in my index.html such that it loads all the fields from the files, moreover I want to display the following output:
的名1 的的Hello World 1 的( ID1 的)的名称2 的的Hello World 2 的( ID2 的) Name1: Hello World 1 (id1) Name2: Hello World 2 (id2)我如何在NG重复束缚这些文件?或有另一种方式?
How can I bind these files in a ng-repeat way? Or is there another way?
推荐答案
您需要先加载它们,然后设置一个包含数组中的必要的数据范围的变量。你可以做 $ HTTP
得到您的控制器(如下面的例子),但如果它是什么,可重复使用的或不是一个简单的应用程序越多,我建议这样做的注入的服务。
You need to load them first, then set up a scope variable that contains the necessary data in an array. You can do the $http
get in your controller (as in the example below), but if it is anything reusable or more than a simple app, I would recommend doing it in an injected service.
.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);
});
});
});
});
,然后你的模板可类似于
and then your template can look something like
<div ng-repeat="entry in entries">
<span>{{entry.name}}: {{entry.description}} ({{entry.id}})</span>
</div>
如果您想订购他们,或装入 $ scope.entries
在一个特定的顺序,或者如果您不想显示任何条目您可以使用过滤器直到所有的准备,那么你可以设置一个现成的变种,或者只设立 $ scope.entries
末等。
You can use filters if you want to order them, or load the $scope.entries
in a particular order, or if you don't want to show any entries until all are ready, then you can set a ready var, or only set $scope.entries
at the end, etc.
让我补充一点,我不喜欢那种越陷越深嵌入式Ajax调用,以及该系列当中,但它是一个风格问题。我已经成为caolan的异步库作出上述控制器code更干净的忠实粉丝。 http://github.com/caolan/async
Let me add that I don't like that kind of deeper and deeper embedded ajax calls, as well as the series of them, but it is a question of style. I have become a big fan of caolan's async library for making the above controller code far cleaner. http://github.com/caolan/async
相关推荐
最新文章