gpt4 book ai didi

javascript - AngularJS : Functions in Service doesn't work

转载 作者:行者123 更新时间:2023-11-28 05:47:50 25 4
gpt4 key购买 nike

所以我正在以 Angular 提供服务,但是当我在 Controller 中调用它时它不起作用......这是服务:

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;
};
});

在我的 Controller 中,我尝试这样调用它:

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

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

$scope.posts = AllPosts.posts;

各位,我做错了什么吗?

最佳答案

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

$scope.posts = AllPosts.getPosts;

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

$scope.posts = AllPosts.getPosts();

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

关于javascript - AngularJS : Functions in Service doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com