angularjs data binding issue

- 1 answer

Ad

I am trying to allow a user to submit a comment, where it can be displayed. However, It doesn't seem to be working properly as I am able to get it to displayed as a preview but when I submit, it does not save as an array where the other comments are held. After debugging, I found out it was binding to my $scope.review, but it was being submitted to my array as a blank default format as shown on the webpage. The source code can be found at http://plnkr.co/edit/q5fRIG6DzTegi3Ir1y8G?p=preview. (Commented out the resetting of pristine state and scope, which also gives same error).

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>
Ad

Answer

Ad

Agree with Lucas, you need to add the object rather than the string. Also your new review field names don't match the existing fields in the existing reviews

.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:""};
            }

        }])

Notice I modified the "name" to "author" and the rating value from "Five" to 5. You will need to check the bindings in the "preview" html to match the changes though!

modified plunk here

Ad
source: stackoverflow.com
Ad