2016-07-12 8 views
1

は、だから私は角度でサービスを作ってるんだけど、私は私のコントローラでそれを呼び出したとき、それは動作しません動作しません... ここでは、サービスである:AngularJS:サービス内の機能が

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(value.id == id){ 
       post=value; 
      } 
     }); 
     return post; 
    }; 
}); 

私は空白のページを持っているが、私は.postsで.getPostsを交換する場合、私は私のページの読み込み権を持つ関数.getPostsを使用しようとすると

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

:私のコントローラで私はそのようにそれを呼び出すようにしてみてください。 ..

$scope.posts = AllPosts.posts; 

私は間違った男をしていますか?あなたが関数に$scope.postsを割り当てているあなたのコードで

+0

をあなたは '$ scope.posts = AllPosts.getPosts()関数を呼び出す必要があり;'。プロのヒント:デベロッパーツールを開きます(WindowsではF12、MacではOpt + Cmd + I)。あなたが困ったときには、多くの助けになります。 –

+0

'AllPosts.getPosts()'についてはどうですか? – developer033

+0

プロのチップをありがとう、私はそれをしましたが、それは間違って何も言わなかった... –

答えて

1

$scope.posts = AllPosts.getPosts(); 

今、$scope.posts

$scope.posts = AllPosts.getPosts; 

メソッド呼び出しの結果は$scope.postsに割り当てられているように、あなたは、関数を呼び出す必要がありますメソッドによって返された投稿に割り当てられます。

-1

私は関数として、または変数として動作するようにコードを編集しました。お使いのコントローラで

app.service('AllPosts', function(){ 
    var posts = [ 
     {"id":"0","username":"Simon", "age":"18"}, 
     {"id":"1","username":"Chris", "age":"53"} 
    ]; 
    this.getPosts = function(){ 
     return this.posts; 
    }; 
    // or you can do this by calling it. 
    this.getPosts = this.posts; 
    // Using functional programming and arrow function. 
    this.getPost = function(id){ 
     return this.posts.filter((value) => { 
      return value.id == id; 
     }); 
    }; 
}); 

:@Amin Meyghaniとして とマイクC @が言及:

app.controller('PostsCtrl', function($scope, AllPosts){ 
    // You need to comment one of these 
    // to use it as a function. 
    $scope.posts = AllPosts.getPosts(); 
    // or if you want to use it as avarible . 
    $scope.posts = AllPosts.getPosts 
}); 
+0

なぜこれがダウン投票されたのか分かりますか? –

関連する問題