Within my controller, the code snippet below is present...
$scope.products = dataService.getJsonData();
console.log($scope.products);
The corresponding code in my dataservice is as follows:
.service('dataService', function ($http) {
this.getJsonData = function () {
return $http.get('path/to/json/products.json').then(function (response) {
// Extract necessary data only
var productData = response.data;
console.log(productData);
return productData;
});
};
Lastly, the code in my view looks like this:
<div ng-repeat="product in products">
Name: {{ product.name }} <br>
Price: {{ product.price }}
<hr>
</div>
Upon rendering the view, I noticed that only 3 items are displayed out of a total of 15 objects in the 'products' array. Surprisingly, when inspecting the console, the log for 'products' appears to be
Object { then=function(), catch=function(), finally=function()}
, while the console output from the dataservice displays the expected object array. This asynchronous behavior is confusing me. How can I make the view wait for the dataservice without resorting to using a $timeout
? Has anyone encountered similar issues before? Thank you for your help.
UPDATE *
After some research online, it seems like adding a resolve block to my $routeProvider might solve the issue. The current configuration for $routeProvider
is as follows:
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
resolve:{
// Placeholder for required action...
}
})