Loading json file with service and use the data in controller and html template

Hi. I’m having issues loading a json file and store the data in controller. I searched for similar problems, but i could not find anything (maybe because i was not using the correct search criteria).


services.js

.factory(“Subscriptions”, [’$http’, function($http) {
var subscriptions = [];

$http.get('subscriptions.json').success(function(data) {
    subscriptions = data;
});

return {
    all: function() {
        return subscriptions;
    },
    get: function(subscriptionId) {
        for (var i = 0; i < subscriptions.length; i++) {
            if (subscriptions[i].subscriptionId === parseInt(subscriptionId)) {
                return subscriptions[i];
            }
        }
        return null;
    }
};

}])

controllers.js

.controller(“SubscriptionsCtrl”, ["$scope", “Subscriptions”, function($scope, Subscriptions) {
$scope.subscriptions = Subscriptions.all();
}])

The problem is, when i go to the page which lists all subscriptions, it all appears blank. I tried to change the code a bit, and that worked, but i did not liked the solution, because i think that’s not the best practice.


$http.get('subscriptions.json').success(function(data) {
    for(var i = 0; i < data.length; i++) {
        subscriptions.push(data[i]);
    }
});

Can you guys help me please?

Note: btw, it would be usefull if ionic would include an example with json file load, instead of hardcoded data.

Hi.

I’m not understanding the right way to share a service between two controllers, and ensure that both are synchronized.

My first page, subscriptions, it’s supposed to fetch an array, and list it in the page. When we click on a subscription, it is supposed to get one of the records in that array.

What’s the best practice for this?

Did you figure this out? I’m struggling with the exact same issue and it’s making me nuts.

Struggling to figure this out as well. Someone help