I follow this guide When I try to post a comment on a post, I get a TypeError: Cannot read property 'comments' of undefined error in my console.
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 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 located in mainCtrl.js .
And here are my part.html and post.html parts that are enabled 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 am redirected to localhost:3000/#/home . Then I can enter the title and publish it. When I click on the comments link, I redirect to http://localhost:3000/#/posts/ , and when I try to post a comment, I get
TypeError: Cannot read property 'comments' of undefined at Scope.$scope.addComment error.