0
我坚持了整整一天。Rails + Angularjs:如何与后端进行通信(从数据库删除记录)?
在http://localhost:3001/posts/
,我列出了我在数据库中的所有帖子。我试图删除任务使用Angularjs - 从数据库中每一个加载的记录有其删除链接:
= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}"
然后,我有一个文件/assets/javascript/angular/controller/posts.js
看起来像这样:
var app = angular.module('AngTestApp', ['ngResource']);
app.factory('Post', function($resource) {
return $resource("/posts/:id", { id: '@id' }, {
index: { method: 'GET', isArray: true, responseType: 'json' },
show: { method: 'GET', responseType: 'json' },
update: { method: 'PUT', responseType: 'json' }
});
})
app.controller("PostsCtrl", function($scope, Post) {
$scope.posts = Post.index();
$scope.deletePost = function(index) {
console.log("index: "+index);
post = $scope.posts[index];
Post.delete(post);
$scope.posts.splice(index, 1);
console.log('aa');
}
})
当我点击删除链接,我收到此错误的JS控制台:
DELETE http://localhost:3001/posts 404 (Not Found)
和终端:
条Started DELETE "/posts" for 127.0.0.1 at 2015-10-15 16:23:08 -0700
ActionController::RoutingError (No route matches [DELETE] "/posts"):
的路线是这样的:
resources :posts do
resources :comments
end
JS代码非常混乱,我试图修改教程中,我在网上找到的,但它不能很好地工作。
这种尝试有什么问题?
预先感谢您。
嗨布拉德,感谢您的回答。我试过,但结果是TypeError:无法在JS控制台中读取'undefined'的属性'delete'。我是否需要在项目中加入一些图书馆? – user984621
嗯,似乎有一个类型的地方,工厂正在返回undefined。你也可以看看这个:https://stackoverflow.com/questions/16167463/angular-js-delete-resource-with-parameter –