我是AngularJS的初学者和新手。我正在尝试构建一个编辑/更新功能。
编辑功能不会做太多,它只是将模型数据复制到表格输入:
// Edit post
$scope.editPost = function(post){
$scope.title = post.title;
$scope.link = post.link;
};
更新功能应该(在点击更新按钮之后)获取输入的编辑数据,以更新帖子模型:
// Update post
$scope.updatePost = function(post){
posts.update(post, {
title: $scope.title,
link: $scope.link
}).success(function() {
ToastService.show('Post updated');
});
};
编辑部分工作,当我编辑标题输入并单击编辑表单的提交按钮时,它发送一个PUT请求,但它似乎没有在PUT内发送更新的数据 - 它只是发送请求包含原始数据。
posts.js服务:
angular.module('bidrp')
.factory('posts', [
'$http',
function($http){
var o = {
posts: [{title:"hey", upvotes:123}]
};
o.update = function(post) {
return $http.put('/posts/' + post.id, post).success(function(data){
o.posts.push(data);
});
};
显示帖子并触发editPost的模板:
<div ng-repeat="post in posts | orderBy: '-upvotes'">
<md-button class="md-icon-button md-accent" aria-label="Vote-Up" ng-click="incrementUpvotes(post)">
<i class="material-icons">thumb_up</i>
</md-button>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
<span>
posted by <a ng-href="#/users/{{post.user.username}}">{{post.user.username}}</a>
</span>
<span>
<a href="#/posts/{{post.id}}">Comments</a>
<a href="#" ng-click="editPost(post); showEditForm = ! showEditForm">Edit</a>
<a href="#" ng-click="deletePost(post)">Delete</a>
</span><br>
<div ng-show="showEditForm" ng-include="'home/_edit-post.html'"></div>
</div>
<div ng-include="'home/_add-post.html'"></div>
_edit-post.html partial:
<form ng-submit="updatePost(post)">
<h3>Edit post</h3>
<div ng-include="'home/_form-post.html'"></div>
</form>
_form-post.html partial:
<md-input-container>
<label>Title</label>
<input required type="text" ng-model="title">
</md-input-container>
<md-input-container>
<label>Link</label>
<input type="text" ng-model="link">
</md-input-container>
<md-button type="submit" class="md-raised md-primary">Submit</md-button>
我做错了什么,如何在PUT请求中发送已编辑的表单数据?
答案 0 :(得分:0)
发生这种情况是因为,您只是将ngRepeat生成的原始post对象传递给更新函数而不是$ scope.post。使用ng-model =“post”时,这将附加到$ scope对象。
您不需要editPost函数,新数据已经通过ngModel指令传递给$ scope.title / $ scope.title(这样做会重新更新$ scope.tile,$ scope.link与旧价值观):
// Edit post
$scope.editPost = function(post){
$scope.title = post.title;
$scope.link = post.link;
};