AngularJS将新数据推送到特定的JSON中

AngularJS Push New Data into Specific JSON

本文关键字:JSON 新数据 数据 AngularJS      更新时间:2023-09-26

JSON输出如下所示:

[{"id":"121","title":"Blog Title","content":"Blog content"}, "comments":[{"id":"12","content":"This is the comment."}]]

我正在通过Angular中的控制器检索数组:

app.controller('BlogController', function($scope, $http) {
    var blog = this;
    blog.posts = [];
    $http.get('/process/getPost.php').success(function (data) {
        blog.posts=data;
    });
    $scope.submitComment = function() {
        blog.posts.concat($scope.formData);
        $http({
            method  : 'POST',
            url     : '/process/insertComment.php',
            data    : $.param($scope.formData),  // pass in data as strings
            headers: {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
        })
        .success(function(data) {
            console.log(data);
            $scope.formData.comment="";
        });
    };
})

然后显示我的index.html文件中的信息:

<div ng-controller="BlogController as blog" ng-cloak class='ng-cloak'>
    <div ng-repeat="post in posts">
        <div>{{post.title}}</div>
        <div>{{post.content}}</div>
    </div>
    <div ng-repeat="comment in post.comments">
        {{comment.content}}
    </div>
    <form name="commentform" ng-init="formData.id=post.id" novalidate>
        <textarea ng-model="formData.comment" name="comment" required></textarea><br>
        <input type="submit" ng-disabled="commentform.$invalid" value="Submit" ng-click="submitComment()">
    </form>
</div>

一切工作,因为它应该,但我一直试图有submitComment()更新评论。JSON数组中的内容,其中博客id等于post。Id,其中注释Id等于comment. Id。

我试过做blog.post.comment.push($scope.formData),但那不起作用。知道为什么它不工作和如何解决它吗?

这可能对你有帮助http://jsbin.com/fatote/2/edit?html,js,output

  $scope.submitComment = function(post) {

    $http.post('/process/insertComment.php', post.formData)
        .then(function(data) {
            console.log(data);
            $scope.formData.comment="";
        }, function(){
          alert("Can't post");
        }).then(function(){
      //finally as we know that post would work in that case
      //find last comment id
          var newCommentId = post.comments[post.comments.length-1].id +1;
      //create new comment obj
      var newComment = {
          id:newCommentId,
          content:post.formData.comment
            };
      //push comment in comments array
       post.comments.push(newComment);
      //clean form
       post.formData.comment="";

    });

    };

您的线路blog.posts.concat($scope.formData);没有被分配到任何地方。注意,.concat不同于.sort,因为您正在创建一个新的数组。

来自MDN:"concat()方法返回一个由该数组与其他数组和/或值连接组成的新数组。"

尝试将行改为blog.posts = blog.posts.concat($scope.formData);

编辑:

我猜你的数据格式,更可能需要的改变是:

var post = blog.posts[blogPostId]; // you'll need to determine blogPostId
post.comments = post.comments.concat($scope.formData);