How to link multiple JSON files in ng-repeat (AngularJS)?
I have several 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",
}
}
Now I want to create an ng-repeat div in my index.html so that it loads all fields from files, moreover, I want to display the following output:
- Name1: Hello World 1 (id1)
- Name2: Hello World 2 (id2)
How do I link these files using ng-repeat? Or is there another way?
source to share
You need to load them first and then set up a scope variable containing the required data in an array. You can do $http
get in your controller (like in the example below), but if it's something reusable or a simpler application, 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 might look something like
<div ng-repeat="entry in entries">
<span>{{entry.name}}: {{entry.description}} ({{entry.id}})</span>
</div>
You can use filters if you want to order them, or load $scope.entries
in a specific order, or if you don't want to show any entries until everything is ready, you can install a pre-made var, or just install $scope.entries
at the end, etc. ...
Let me add that I don't like the deeper and deeper inline ajax calls like this and the series of them, but it's a matter of style. I've become a big fan of the caolan async library to make the code above the controller much cleaner. http://github.com/caolan/async
source to share
Simple way:
ANSI SQL analog UNION operator.
For more info see example https://docs.angularjs.org/api/ng/directive/ngInit
<script>
angular.module('initExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [['a', 'b'], ['c', 'd']];
}]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
</div>
Result:
list[ 0 ][ 0 ] = a;
list[ 0 ][ 1 ] = b;
list[ 1 ][ 0 ] = c;
list[ 1 ][ 1 ] = d;
source to share