angularjs数据绑定问题

时间:2015-12-18 01:12:42

标签: javascript angularjs

我正在尝试允许用户提交评论,以便在其中显示。但是,它似乎没有正常工作,因为我能够将其显示为预览,但是当我提交时,它不会保存为其他注释所在的数组。调试后,我发现它绑定到我的$ scope.review,但是它被提交到我的阵列,作为网页上显示的空白默认格式。源代码可以在http://plnkr.co/edit/q5fRIG6DzTegi3Ir1y8G?p=preview找到。 (注释掉了原始状态和范围的重置,这也给出了相同的错误)。

的Javascript

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

        $scope.review = {name:"", rating:"Five", comment:"",date:""};
            $scope.submitComment = function () {

            $scope.review.date = new Date().toISOString();

            //  Push comment into the dish's comment array
            $scope.dish.comments.push("$scope.review");
             //reset  form to pristine
           // $scope.commentForm.$setPristine="";
             //reset  JavaScript object that holds your comment
           // $scope.review = {name:"", rating:"Five", comment:"",date:""};
        }

HTML

        <div class="media-list">
                <ul ng-show="!commentForm.comment.$error.required && !commentForm.comment.$pristine && !commentForm.name.$error.required && !commentForm.name.$pristine">
                    <blockquote>
                        <p>{{review.rating}} Stars</p>
                        <p>{{review.comment}}</p>
                        <footer>By {{review.name}} on {{review.date | date:'mediumDate'}} </footer>
                    </blockquote>
                </ul>
            </div>

3 个答案:

答案 0 :(得分:1)

你需要推送对象:

$scope.dish.comments.push($scope.review);

答案 1 :(得分:1)

您正在推送一个字符串,而您需要推送一个对象:

$scope.dish.comments.push($scope.review);

此外,$scope.dish.comments属于DishDetailControllersubmitComment方法属于DishCommentController。范围是控制器定义的,因此他们不会知道彼此的存在。

如果您希望共享范围

,则需要将方法放在同一个控制器中

答案 2 :(得分:0)

同意Lucas,您需要添加对象而不是字符串。此外,您的新审核字段名称与现有评论中的现有字段不匹配

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

            $scope.review = {
                                   rating:5,
                                   comment:"",
                                   author:"",
                                   date:""
                               };
                $scope.submitComment = function () {

                $scope.review.date = new Date().toISOString();

                //  Push comment into the dish's comment array
                $scope.dish.comments.push($scope.review);
                 //reset  form to pristine
                $scope.commentForm.$setPristine="";
                 //reset  JavaScript object that holds your comment
                $scope.review = {author:"", rating:5, comment:"",date:""};
            }

        }])

注意我将“name”修改为“author”,将评级值从“Five”修改为5.您需要检查“preview”html中的绑定以匹配更改!

修改了plunk here

相关问题