Reputation: 541
Now, this might be theoretical question and since I'm still learning AngularJS, please forgive me dumbness.
Is there a way to make Angular to call lets say 3 json files, from various locations, and they all have the same layouts and then with one call "compile" or "load" it as one, to increase loading time?
Lets say we have 3 json files:
1st JSON file:
{
"name": "John",
"sur": "Smith"
}
2nd JSON file:
{
"name": "John",
"sur": "Doe"
}
3rd JSON file:
{
"name": "Alice",
"sur": "Mulder"
}
What would be the most effective and fastest way to call them and then show them, using ng-repeat
? Theoretically, can they be compiled in one "temporary json file" just before we decide to input them into the html using expressions?
Upvotes: 0
Views: 292
Reputation: 8056
Ultimately you will want to bind a single array to your view. This ng-repeat
will iterate through every item in the array, and pretty-print each object into a <pre/>
:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-repeat="entry in entries">
<pre ng-bind="entry | json"></pre>
</div>
</div>
</div>
Begin 3 $http.get()
requests concurrently (obviously you can change these to file1.json
, file2.json
, etc).
Every $http.get()
promise gives us a response
object when it completes. We actually want response.data
instead (gives us the response, parsed as JSON), so Array.prototype.map()
your every promise for a response
such that it becomes instead a promise for a response.data
.
Then use $q.all()
to wait for all these promises to complete.
Once the $q.all()
promise completes: we have our array of JSON responses. Add that model to our $scope
.
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope, $http, $q) {
$q.all(
[
$http.get('https://httpbin.org/get'),
$http.get('https://httpbin.org/get'),
$http.get('https://httpbin.org/get')
]
.map(function(promise) {
return promise
.success(function(response) {
return response.data;
})
})
)
.then(function(multipleJson) {
$scope.entries = multipleJson;
})
});
Plunkr here.
Upvotes: 2