0

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?

Community
  • 1
  • 1
ctrlawkdel
  • 15
  • 3

1 Answers1

0

your promise is not completed when you are setting your variable. Change your factory to return a function and then call the function in your controller.

var pageApp = angular.module('pageApp', []);

pageApp.controller('productStreamCtrl', function($scope, ProductStreamService) {
    ProductStreamService.getProducts().then(function(data){
        $scope.products = data;
    }); 
});

pageApp.factory('ProductStreamService', function($http) { 


    function getProducts(){
       return $http.get('products.json').then(function(data) {
            return data;
        }); 
    } 

    return {getProducts: getProducts};
});
M B
  • 2,326
  • 24
  • 33
  • Thank you! One minor change: the 'then' function should pass a variable other than data, and data should be a property of that variable. `then(function(result){return result.data;});` – ctrlawkdel Dec 02 '16 at 16:02