我正在关注本教程,当我尝试在帖子上发表评论时,TypeError: Cannot read property 'comments' of undefined
控制台出现错误。
mainCtrl,
.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 = '';
};
}
])
两个控制器都在中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
错误。
您已经定义了两个单独的控制器,不需要这样做。如果再次查看该教程,您将看到addPost和addComment函数位于单个控制器内,如下所示
.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 = '';
};
}]);
在预先定义了comment属性的单个Post对象上添加post和comment即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句