加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:58:36 所属栏目:安全 来源:网络整理
导读:I’m following this tutorial当我尝试在帖子上发表评论时,我得到一个TypeError:无法在我的控制台中读取未定义错误的属性“评论”. mainCtrl, .controller('mainCtrl',['$scope','posts',function($scope,posts){ $scope.posts = posts.posts; $scope.addPo
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属性.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读