Codehan25 Codehan25 - 4 months ago 17
AngularJS Question

AngularJS (Loading JSON with custom Service)

I'm trying to built a service for loading json files. What am I doing wrong?

The Service

app.service("jsonService", function ($http, $q)
{
var deferred = $q.defer();

$http.get('./assets/json/home.json').then(function (data)
{
deferred.resolve(data);
});

this.getHomeItems = function ()
{
return deferred.promise;
}
})


My Controller

app.controller('homeController', function ($scope, jsonService) {

var promise = jsonService.getHomeItems();
promise.then(function (data)
{
$scope.home_items = data;
console.log($scope.home_items);
});

});


Console Error: $scope is not defined

Answer

You are missing the dependency injection.

Your service should be:

app.service("jsonService", ["$http", "$q", function ($http, $q)
{
    var deferred = $q.defer();

    $http.get("./assets/json/home.json").then(function (data)
    {
        deferred.resolve(data);
    });

    this.getHomeItems = function ()
    {
        return deferred.promise;
    }
}]);

And your Controller:

app.controller("homeController", ["$scope", "jsonService", function ($scope, jsonService)
{
    var promise = jsonService.getHomeItems();
    promise.then(function (data)
    {
        $scope.home_items = data;
        console.log($scope.home_items);
    });
}]);
Comments