I'm following this tutorial When I try to post a comment on a post I get a TypeError: Cannot read property 'comments' of undefined error in my console.
the 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}
]
});
};
}
])
and the 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 = '';
};
}
])
Both controllers are in mainCtrl.js.
And here are my home.html and post.html partials which are being included through 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
When I visit the homepage I get redirected to localhost:3000/#/home I can then enter a title and post it. When I click on the comments link I get redirected to http://localhost:3000/#/posts/ and when I try to post a comment I get the
TypeError: Cannot read property 'comments' of undefined at Scope.$scope.addComment error.
mainCtrlyou have$scope.posts.and in themainCtrlyou have$scope.post.Could you try to rename$scope.post.to$scope.posts.and see if that works?$scope.posttot$scope.postsdidn't change anything. And I've addedconsole.log($scope.postjust beneath the$scope.post = posts.posts[$stateParams.id];line and I'm getting aundefinedoutput in the console.