Simon Valère Trichereau Simon Valère Trichereau - 3 months ago 7x
Javascript Question

AngularJS : Functions in Service doesn't work

So I'm making a service in angular but when I call it in my controller it doesn't work...
Here is the service :

app.service('AllPosts', function(){
this.posts = [
{"id":"0","username":"Simon", "age":"18"},
{"id":"1","username":"Chris", "age":"53"}
this.getPosts = function(){
return this.posts;
this.getPost = function(id){
var post={};
angular.forEach(this.posts, function(value) {
if( == id){
return post;

And in my controller I try to call it like that:

app.controller('PostsCtrl', function($scope, AllPosts){
$scope.posts = AllPosts.getPosts;

When I try to use the function .getPosts I have an empty white page but if I replace .getPosts by .posts I have my page loading right...

$scope.posts = AllPosts.posts;

What am I doing wrong guys, please?


In your code you are assigning $scope.posts to a function:

$scope.posts = AllPosts.getPosts;

You should call the function so that the result of the method call is assigned to $scope.posts:

$scope.posts = AllPosts.getPosts();

Now, $scope.posts will be assigned to the posts that are returned by the method.