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

时间:2014-07-08 18:29:43

标签: javascript json angularjs

我有一个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数组中更新comment.content,其中blog id等于post.id,注释id等于comment.id。

我尝试过做blog.post.comment.push($ scope.formData),但是没有用。知道为什么它不起作用以及如何解决它?

2 个答案:

答案 0 :(得分:0)

您的专线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);

答案 1 :(得分:0)

这可能对您有所帮助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="";


    });


    };