I have an angular controller that calls a service. The service is responsible for returning data from a json file.
controller:
function projectController
$http
is asynchronous, therefore the call to getProjects
will return nothing. Using $q
you can receive an instance to a promise which will receive the data when available.
Using $q
Here an example using $q
:
http://plnkr.co/edit/U72oJblvrVEgYt2mTmU2?p=preview
Using $resource
Alternatively, you can use $resource
especially if your server code is RESTful, which requires adding the following dependency in your scripts:
//ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular-resource.js
This is a 1st review of your code to use $resource
: http://plnkr.co/edit/tLOAaXZHdGgWOok3Sdc8?p=preview
But you can simplify and shrink it more to this: http://plnkr.co/edit/pKO6k6GxJ1RlO8SNvqUo?p=preview
This is the new app.js
file:
angular.module('app', ['ngResource'])
.factory('ProjectsService', ['$resource', function($resource) {
return $resource('projects.json');
}])
.controller('ProjectsController', ['ProjectsService', '$scope', function(ProjectsService, $scope) {
$scope.projects = ProjectsService.query();
}]);
Find more information about $resource
here:
http://docs.angularjs.org/api/ngResource.$resource