【问题标题】:Refreshing DIV with AngularJS and Rails on backend在后端使用 AngularJS 和 Rails 刷新 DIV
【发布时间】:2015-10-16 15:28:09
【问题描述】:

我使用 `ng-click' 来使用 AngularJS 从我的数据库中删除帖子。

%table.table{"ng-controller" => "PostsCtrl"}
  %tr
    %th Title
    %th ....
    %th
  - @posts.each do |post|
    %tr
      %td...
      %td= link_to 'Delete', '', 'ng-click' => "deletePost('#{post.id}')", :id => "post_#{post.id}"

这是/app/views/posts/index.html.haml

以及它的行动:

 def index
   @posts = Post.all
 end

现在是 JS:

var app = angular.module('MyApp', ['ngResource']);
app.factory('Posts', function($resource){
 return $resource('/posts.json', {},{
    query: { method: 'GET', isArray: true },
    create: { method: 'POST' }
 })
});

app.factory('Post', function($resource) {
    return $resource("/posts/:id", { id: '@id' }, {
        'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
    });
});
app.controller("PostsCtrl", ['$scope', '$http', '$resource', 'Posts', 'Post', '$location', function($scope, $http, $resource, Posts, Post, $location) {

$scope.posts = Posts.query();
$scope.deletePost = function (post_id) {
    if (confirm("Are you sure you want to delete this user?")){
      Post.delete({ id: post_id }, function(){
        $scope.posts = Posts.query(); 

        $location.path('/');
        $scope.$apply();
      });
    }
  };
}]);

当我点击删除帖子的链接时,该记录已从数据库中删除,但在 JS 控制台中抛出以下错误消息:

DELETE http://localhost:3001/posts/5620a8766f85ce82ce000002 406 (Not Acceptable)

这是 Rails 操作:

  def destroy
    puts "test"
    respond_with @post.destroy!
  end

还有routes.rb:

resources :posts do
  resources :comments
end

删除记录后如何消除错误并刷新表?

提前谢谢你。

编辑:

我刚刚发现,如果我单击链接删除相应的帖子,AngularJS 会以 HTML 格式发送请求?从我在终端看到的情况来看:

Processing by PostsController#destroy as HTML
...
ActionController::UnknownFormat - ActionController::UnknownFormat:
...

【问题讨论】:

    标签: javascript ruby-on-rails ruby angularjs


    【解决方案1】:

    正如您所说的 406 错误表明您的后端无法以请求的格式(此处为 HTML )响应。 一种可能的解决方案是在您的请求中指定 json 格式,例如:

    注意:id之后的.json

    app.factory('Post', function($resource) {
        return $resource("/posts/:id.json", { id: '@id' }, {
            'destroy': { method: 'DELETE', params: {id: '@id', responseType: 'json'} }
        });
    });
    

    【讨论】:

    • 感谢 Yann,这就是诀窍!这么小的更新,我为此奋斗了很长时间。请问如何刷新PostsCtrl?我需要手动刷新 (F5) 页面以查看更改。 $scope.$apply(); 在那里不起作用。
    • 我有一段时间不使用 angular,但提示是从您的 $scope.posts 中删除您的帖子,并且不要尝试查询您的所有帖子(导致异步请求)。查看 lodash 或下划线库,这有助于处理 javascript 集合。
    猜你喜欢
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    相关资源
    最近更新 更多