AngularJS Load Data from Service

I think this should solve your problem

app.factory('nukeService', function($rootScope, $http) {
    var nukeService = {};

    nukeService.data = {};

    //Gets the list of nuclear weapons
    nukeService.getNukes = function() {
        $http.get('nukes/nukes.json')
            .success(function(data) {
                nukeService.data.nukes = data;
            });

        return nukeService.data;
    };

    return nukeService;
});

function NavigationCtrl($scope, $http, nukeService){

    $scope.data = nukeService.getNukes();

    //then refer to nukes list as `data.nukes`

}

This is a problem with object reference.

when you calls nukeService.getNukes() you are getting a reference to a object a then your variable $scope.nukes refers that memory location.

After the remote server call when you set nukeService.nukes = data; you are not changing the object a instead you are changing nukeService.nukes from referencing object a to object b. But your $scope.nukes does not know about this reassignment and it still points to object a.

My solution in this case is to pass a object a with property data and then only change the data property instead of changing reference to a

Leave a Comment