在javascript中将新元素推送到数组时出错

Posted

技术标签:

【中文标题】在javascript中将新元素推送到数组时出错【英文标题】:error when pushing new element to array in javascript 【发布时间】:2017-06-17 10:17:19 【问题描述】:

我正在尝试将 html 表单元素中的 cmets 添加到 angularjs 中的数组中。当我使用 javascipt 推送功能时,出现错误“对象的属性不存在”。 有人可以帮我解决这个问题。您可以在下面找到我的 javascript 和 html 代码:

感谢您的阅读

    .controller('DishDetailController', ['$scope', function($scope) 

            var dish=
                          name:'Uthapizza',
                          image: 'images/uthapizza.png',
                          category: 'mains', 
                          label:'Hot',
                          price:'4.99',
                          description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                           comments: [
                               
                                   rating:5,
                                   comment:"Imagine all the eatables, living in conFusion!",
                                   author:"John Lemon",
                                   date:"2012-10-16T17:57:28.556094Z"
                               ,
                               
                                   rating:4,
                                   comment:"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                                   author:"Paul McVites",
                                   date:"2014-09-05T17:57:28.556094Z"
                               ,
                               
                                   rating:3,
                                   comment:"Eat it, just eat it!",
                                   author:"Michael Jaikishan",
                                   date:"2015-02-13T17:57:28.556094Z"
                               ,
                               
                                   rating:4,
                                   comment:"Ultimate, Reaching for the stars!",
                                   author:"Ringo Starry",
                                   date:"2013-12-02T17:57:28.556094Z"
                               ,
                               
                                   rating:2,
                                   comment:"It's your birthday, we're gonna party!",
                                   author:"25 Cent",
                                   date:"2011-12-02T17:57:28.556094Z"
                               
                               
                           ]
                    ;
            
            $scope.dish = dish;
            
        ])

        .controller('DishCommentController', ['$scope', function($scope) 


            $scope.newcomment = 
                rating : "",
                comment: "",
                author: "",
                date: new Date().toISOString()
        ;
            $scope.submitComment = function () 
                
                //Step 2: This is how you record the date


                $scope.dish.comments.push($scope.newcomment);
                
              
            
        ])

;
<!DOCTYPE html>
<html lang="en" ng-app="confusionApp">

<head>
     <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  
       <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-social.css" rel="stylesheet">
    <link href="styles/mystyles.css" rel="stylesheet">
<!-- endbuild -->

   
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

    <div class="container">
        <div class="row row-content" ng-controller="DishDetailController">
            <div class="media" ng-model="dish">
                <div class="media-left media-middle">
                    <a href="#">
                        <img class="media-object img-thumbnail" ng-src=dish.image >
                    </a>
                </div>
                <div class="media-body">
                    <h2 class="media-heading"> dish.name
                        <span class="label label-danger">
            dish.label
        </span>
                        <span class="badge">
            dish.price | currency
        </span>
                    </h2>
                    <p>dish.description</p>
                </div>

            </div>
        </div>
        <br>
        <br>
        <br>

        <div class="col-xs-9 col-xs-offset-1" ng-controller="DishDetailController">
            <h4>Customer Comments</h4> Sort by:
            <input type="text" ng-model="filterText">
            <blockquote ng-repeat="commentla in dish.comments | orderBy: filterText">
                <p class="mb-0">  commentla.rating Stars </p>
                <p class="mb-0">commentla.comment</p>
                <footer class="blockquote-footer"> commentla.author commentla.date | date: 'mediumDate' </footer>
            </blockquote>
        </div>
    </div>

            <div class="col-xs-9 col-xs-offset-1" ng-controller="DishCommentController">
                    <ul class="list-unstyled">
                   Your Name: newcomment.author
                        <br>
                        Comment:  newcomment.comment
                        <br>
                        Your Rating: newcomment.rating


					<!--	<p>Task 3: Here you include the code to show the live preview of the comment</p>
						<p>The comment should be shown only when the form contains valid
						information and is not pristine</p> -->
                    </ul>
                <form class="form-horizontal" name="commentForm" ng-submit="submitComment()" novalidate>
                    <div class="form-group">
                        <label for="yname" class="col-sm-2 control-label">Your Name:</label>
                        <div class="col-sm-10">
                        <input type="text" class="form-control" id="yname" aria-des                <div class="col-sm-10">
                        <label class="radio-inline">
                            <input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="1" ng-model="newcomment.rating"> 1
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="inlineRadioOptions" id="inlineRadio2" value="2" ng-model="newcomment.rating"> 2
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="inlineRadioOptions" id="inlineRadio3" value="3" ng-model="newcomment.rating"> 3
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="inlineRadioOptions" id="inlineRadio4" value="4" ng-model="newcomment.rating"> 4
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="inlineRadioOptions" id="inlineRadio5" value="5" ng-model="newcomment.rating"> 5
                        </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="commentm" class="col-sm-2 control-label">Your Comment</label>
                        <div class="col-sm-10">
                            <textarea class="form-control" id="commentm" name="commentm" rows="12" ng-model="newcomment.comment"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary" ng-disabled="feedbackForm.$invalid">Submit Comment</button>
                        </div>
                      
                    </div>
                </form>

        </div>
    </div>

<!-- build:js scripts/main.js -->
    <script src="../bower_components/angular/angular.min.js"></script>
    <script src="scripts/app.js"></script>
<!-- endbuild -->

</body>

</html>

【问题讨论】:

请尝试将其简化为MCVE,因为此过程通常会导致解决方案,而如果没有解决方案,则更容易回答。 在 Angular 中,作用域镜像 DOM 层次结构,因此作用域只能从其祖先作用域继承属性,rootscope 在顶层。范围不会从其任何后代或任何兄弟姐妹继承,这是(看起来)您期望发生的事情。 非常感谢。我试图将其创建为 rootscope。即使在这种情况下,它也不会推送到数组。我删除了第二个作用域添加到第一个作用域的功能。无论我做了什么,它都不会向数组添加新元素。 嗯,我很茫然。不知道还有什么建议:( 天啊,我解决了问题。问题是一个 在 Html 中,我在从 html 代码访问第二个范围之前关闭了它。所以我花了三天时间)))))))只有一个 【参考方案1】:

我相信这与每个控制器的范围有关。您在DishDetailController 中定义dish.comments,而您的提交功能在DishCommentController 控制器中。

尝试将submitcomment 函数从DishCommentController 控制器转移到DishDetailController 控制器,因为DishCommentController 的作用域中甚至没有$scope.dish.cmets。

编辑:按照建议更新代码后,试一试

 .controller('DishDetailController', ['$scope', function($scope) 

    var $scope.dish =
                  name:'Uthapizza',
                  image: 'images/uthapizza.png',
                  category: 'mains', 
                  label:'Hot',
                  price:'4.99',
                  description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                  comments: [
                       
                           rating:5,
                           comment:"Imagine all the eatables, living in conFusion!",
                           author:"John Lemon",
                           date:"2012-10-16T17:57:28.556094Z"
                       
                       ...
                   ]
            ;

    $scope.newcomment = 
        rating : "",
        comment: "",
        author: "",
        date: new Date().toISOString()
    ;

    $scope.submitComment = function (rating , author, stars, date) 
        $scope.dish.comments.push($scope.newcomment);     
    

]);

我删除了一些额外的代码,您可以稍后在它开始工作时添加回来。

<div class="row row-content" ng-controller="DishDetailController">          

        <div class="col-xs-9 col-xs-offset-1">
            <h4>Customer Comments</h4> Sort by:
            <input type="text" ng-model="filterText">
            <blockquote ng-repeat="commentla in dish.comments | orderBy: filterText">
                <p class="mb-0">  commentla.rating Stars </p>
                <p class="mb-0">commentla.comment</p>
                <footer class="blockquote-footer"> commentla.author commentla.date | date: 'mediumDate' </footer>
            </blockquote>
        </div>    

    <div class="col-xs-9 col-xs-offset-1">
            <ul class="list-unstyled">
           Your Name: newcomment.author
                <br>
                Comment:  newcomment.comment
                <br>
                Your Rating: newcomment.rating

            </ul>
        <form class="form-horizontal" name="commentForm" ng-submit="submitComment()" novalidate>
            <div class="form-group">
                <label for="yname" class="col-sm-2 control-label">Your Name:</label>
                <div class="col-sm-10">
                <input type="text" class="form-control" id="yname" aria-des                <div class="col-sm-10">
                <label class="radio-inline">
                    <input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="1" ng-model="newcomment.rating"> 1
                </label>
                ..
            </div>
            <div class="form-group">
                <label for="commentm" class="col-sm-2 control-label">Your Comment</label>
                <div class="col-sm-10">
                    <textarea class="form-control" id="commentm" name="commentm" rows="12" ng-model="newcomment.comment"></textarea>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-primary" ng-disabled="feedbackForm.$invalid">Submit Comment</button>
                </div>

            </div>
        </form>
    </div>
</div>

【讨论】:

感谢您的评论。我也试过了。但是我在做什么我只是得到一个错误:无法读取未定义的属性'cmets' @AgilYolchuyev 我不知道为什么你有这么多 ng-controllers 甚至是只用于单一功能的控制器 我改变了javascript部分。 @AgilYolchuyev 看看它现在的结构 非常感谢您的所有 cmets。感谢您对我的帮助。我也是这样做的。问题是我仍然收到错误:TypeError: Cannot read property 'cmets' of undefined at b.$scope.submitComment (app.js:169)。我的问题是,在视图部分(html 代码)中我有实时预览,并且在 console.log 中它显示了正常结果。但我认为推送到数组部分的问题,我不知道是什么原因。

以上是关于在javascript中将新元素推送到数组时出错的主要内容,如果未能解决你的问题,请参考以下文章

如何在 MySQL 中将元素推送到 JSON

推送到数组时,值被重复

如何在 angularjs 中将元素推送到 http.put 中的数组?

在 Bash 的 heredoc 中将新值推送到数组

在将元素推送到 HTML ID 时更新实时 JavaScript 数组

如何正确地将具有多个元素的新对象推送到数组中?