Fresh developer Fresh developer - 22 days ago 6
JSON Question

How to push entered text in field input and textarea to json angular

How do I place comments with Angular, when someone is clicking on the button. Everytime if I enter some text in the field input and textarea, the text will be gone. There will be an empty block showing without any name, country and comments. The entered text must be push after the existing json.



angular.module("forum-page", ["myApp"])
.controller("Forum", function($scope) {
$scope.comments = [
{
"name": "Kevin",
"comment": "Wat een mooi toestel vandaag ontvangen, zeer blij met mijn bestelling :)",
"country": "Nederland"
},
];

$scope.addComment = function() {
$scope.comments.push({"name": $scope.name, "comment": $scope.comment, "country": $scope.country});

$scope.dataObject = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};

$scope.name = "";
$scope.comment = "";
$scope.country = "";
};
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<tr>
<tr><input type="text" id="comment-name" class="comment-form" ng-model="dataObject.name"/></tr>
<tr><input type="text" id="comment-country" class="comment-form" ng-model="dataObject.country"/></tr>
<tr><textarea type="text" id="comment-box" class="comment-form" ng-model="dataObject.comment"/></textarea></tr>
<tr><button ng-click="addComment()">Place comment</button></tr>
</tr>




Answer

Push dataObject to comments array and create new dataObject with empty fields:

<table ng-app="forum-page" ng-controller="Forum">
<tr ng-repeat="comment in comments">
    <td>{{comment.name}}</td>
    <td>{{comment.comment}}</td>
    <td>{{comment.country}}</td>
    <td></td>
</tr>

<tr>
    <td><input type="text" id="comment-name" class="comment-form" ng-model="dataObject.name"/></td>
    <td><input type="text" id="comment-country" class="comment-form" ng-model="dataObject.country"/></td>
    <td><textarea type="text" id="comment-box" class="comment-form" ng-model="dataObject.comment"/></textarea></td>
    <td><button ng-click="addComment()">Place comment</button></td>
</tr>
</table>


<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
angular.module("forum-page", [])
.controller("Forum", function($scope) {
  $scope.comments = [
    {
      "name": "Kevin", 
      "comment": "Wat een mooi toestel vandaag ontvangen, zeer blij met mijn bestelling :)", 
      "country": "Nederland"
    }, 
  ];

  $scope.addComment = function() {
    $scope.comments.push($scope.dataObject);

    $scope.dataObject = {
      name: '', 
      comment: '', 
      country: ''
    }; 
  };
});
</script>