I would like to read an array in from a JSON file and place it into a Factory so it can be used as a service, then use the service to populate an ng-repeat. This would all happen when the page loaded.
HTML:
<div ng-app="pageApp" ng-controller="productStreamCtrl">
<div ng-repeat="product in products">
<div>
{{product.title}}
</div>
<div>
{{product.descr}}
</div>
</div>
</div>
JS (from this question):
var pageApp = angular.module('pageApp', []);
pageApp.controller('productStreamCtrl', function($scope, ProductStreamService) {
$scope.products = ProductStreamService.obj.products; //Not sure how to call my array?
});
pageApp.factory('ProductStreamService', function($http) {
var obj = {products:null};
$http.get('products.json').then(function(data) {
obj.products = data;
});
return obj;
});
JSON:
[{
"title" : "Title 1",
"descr" : "Description for product 1"
},{
"title" : "Title 2",
"descr" : "Description for product 2"
},{
"title" : "Title 3",
"descr" : "Description for product 3"
},{
"title" : "Title 4",
"descr" : "Description for product 4"
}]
When I run all of this code together, I just get a blank screen. I have been able to display the array in the ng-repeat with an $http.get() call directly in the controller (from this question, see code below)...
pageApp.controller('productStreamCtrl', function($scope, $http) {
$http.get('products.json')
.then(function(result){
$scope.products = result.data;
});
...but I want this array to be accessible globally. I can't seem to get the factory to work.
I think the issue might be with how I'm calling my array from the service or with asynchronous transfer. I do get a JSON syntax error, but I get the same error with the working controller example. Any ideas?