AngularJS将新数据推送到特定的JSON中
AngularJS Push New Data into Specific JSON
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);
相关文章:
- 不显示带有本地json文件数据的谷歌地图脚本
- 正在读取JSON,数据未显示
- 使用Javascript/JQuery获取JSON GET数据
- 如何在ng-reeat中使用ng-switch来编辑JSON API数据
- 如何使用jQuery按键搜索和获取json行数据
- 添加新数据时D3.JS条形图列偏移量
- 将json提要数据显示为html
- 将JSON API数据获取到html
- 使用2个控制器管理工厂JSON$http数据
- 停止JSON.parse()从JSON字符串数据中删除尾随零
- 使用Angular JS for WordPress JSON API使用JSON操作数据
- SVG使新数据保持可见
- 使用新数据更新 D3 饼图.json
- 如何将 json 类型数据追加到新的表单数据
- 在滚动时没有获取新数据,而是在滚动时一次又一次地添加相同的 json 数据
- 将新数据写入javascript变量并解析JSON
- 可以't向我的简单JSON($scope.customers)中添加新数据
- AngularJS将新数据推送到特定的JSON中
- JSON新数据推送.如何保存更改?与AngularJs
- 从JSON向现有表添加新数据