gpt4 book ai didi

angularjs - 类型错误 : Cannot read property 'comments' of undefined using Angular

转载 作者:行者123 更新时间:2023-12-04 15:56:15 25 4
gpt4 key购买 nike

I'm following this tutorial当我尝试对帖子发表评论时,我收到了 TypeError: Cannot read property 'comments' of undefined我的控制台中的错误。

主要的Ctrl,

.controller('mainCtrl', ['$scope', 'posts',
function($scope, posts){
$scope.posts = posts.posts;

$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { alert("Field can't left blank"); return; }

$scope.posts.push({
title: $scope.title,
upvotes: 0,
comments: [
{author: 'Joe', body: 'Cool post!', upvotes: 0},
{author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0}
]
});
};
}
])

和 postCtrl,
.controller('PostsCtrl', ['$scope', '$stateParams', 'posts',
function($scope, $stateParams, posts){
$scope.post = posts.posts[$stateParams.id];

$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};

}
])

两个 Controller 都在 mainCtrl.js .

这是我的 home.html 和 post.html 部分文件,它们通过 router-ui 包含在内。
%script{:id => "/home.html", :type => "text/ng-template"}
%h1
Flappernews

%a{:href => "#/posts/{{$index}}"} Comments

%script{:id => "/posts.html", :type => "text/ng-template"}
%h2
Below here should be comments
%span
{{ post.comments }}
%div{"ng-repeat" => "comment in post.comments | orderBy:'-upvotes'"}
{{comment.upvotes}} - by {{comment.author}}
%span{:style => "font-size:20px; margin-left:10px;"}
{{comment.body}}

%form{"ng-submit" => "addComment()"}
%h3 Add a new comment
.form-group
%input.form-control{"ng-model" => "body", :placeholder => "Comment", :type => "text"}
%button.btn.btn-primary{:type => "submit"} Post

当我访问主页时,我被重定向到 localhost:3000/#/home然后我可以输入标题并发布它。当我点击 comments链接我被重定向到 http://localhost:3000/#/posts/当我尝试发表评论时,我得到了
TypeError: Cannot read property 'comments' of undefined at Scope.$scope.addComment错误。

最佳答案

您已经定义了两个单独的 Controller ,不需要这样做。如果您再次查看该教程,您将看到 addPost 和 addComment 函数在像这样的单个 Controller 中

   .controller('PostsCtrl', [
'$scope',
'$stateParams',
'posts',
function($scope, $stateParams, posts){

// Fetch post object from state parameter.
$scope.post = posts.posts[$stateParams.id];

// Add Post.
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: 0,
comments: [
{author: 'Joe', body: 'Cool post!', upvotes: 0},
{author: 'Bob', body: 'Great idea but everything is wrong!', upvotes: 0}
]
});

// Add comment.
$scope.addComment = function(){
if($scope.body === '') { return; }
$scope.post.comments.push({
body: $scope.body,
author: 'user',
upvotes: 0
});
$scope.body = '';
};

}]);

添加帖子和评论适用于预先定义了评论属性的单个帖子对象。

关于angularjs - 类型错误 : Cannot read property 'comments' of undefined using Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31964068/

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