2014-07-08 19 views
0

我有一個JSON輸出看起來像這樣:AngularJS推新數據到具體JSON

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

我檢索陣列通過控制器角度:

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> 

一切正常,因爲它應該但我一直在試圖讓submitC omment()更新JSON數組內的comment.content,其中博客ID等於post.id,其中評論ID等於comment.id。

我試過做blog.post.comment.push($ scope.formData),但沒有奏效。任何想法爲什麼它不工作,以及如何解決它?

+3

這不是有效的JSON:S – PixnBits

+0

你能澄清這個問題嗎? –

+0

嗨作爲帖子是發佈數組,你需要更具體到哪個帖子你想添加評論和@PixnBits提到你的JSON也是無效 – sylwester

回答

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=""; 


    }); 


    }; 
+0

這導致我回答我的答案。我最終需要將formData傳遞給submitComment(),然後將formData添加到變量函數並使用它來清除數據。 – mattshull

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);