AngularJS:服务中的函数不起作用

时间:2016-07-12 22:36:16

标签: javascript angularjs function 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(value.id == id){
                post=value;
            }
        });
        return post;
    };
});

在我的控制器中,我试着这样称呼它:

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

当我尝试使用.getPosts函数时,我有一个空的白页,但如果我用.posts替换.getPosts,我的页面加载正确...

$scope.posts = AllPosts.posts;

我做错了什么,拜托?

2 个答案:

答案 0 :(得分:1)

在您的代码中,您将$scope.posts分配给函数:

$scope.posts = AllPosts.getPosts;

您应该调用该函数,以便将方法调用的结果分配给$scope.posts

$scope.posts = AllPosts.getPosts();

现在,$scope.posts将分配给方法返回的帖子。

答案 1 :(得分:-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和@ Mike 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
});