微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angularjs – TypeError:无法使用Angular读取undefined的属性’comments’

I’m following this tutorial当我尝试在帖子上发表评论时,我得到一个TypeError:无法在我的控制台中读取未定义错误属性评论”.

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','$stateParams',$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我可以输入标题并发布.当我点击评论链接时,我被重定向到http:// localhost:3000 /#/ posts /当我尝试发表评论时,我得到了

TypeError:无法读取Scope中未定义的属性“comments”.$scope.addComment错误.

解决方法

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

.controller('PostsCtrl',[
    '$scope',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}
      ]
    });

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

    }]);

在单个Post对象上添加发布和评论工作,其中预定义了comments属性.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐