Javascript rails中的angularjs:将数据添加到数据库并显示,无需重新加载

Javascript rails中的angularjs:将数据添加到数据库并显示,无需重新加载,javascript,ruby-on-rails,ajax,angularjs,Javascript,Ruby On Rails,Ajax,Angularjs,在rails项目中,我从angularjs控制器通过http.post向数据库添加数据。我有以下代码来执行此操作: RestaurantIndexCtrl.js.coffee: restauranteur.controller 'RestaurantIndexCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) -> $scope.restaurants = [] $http.get('./restaura

在rails项目中,我从angularjs控制器通过
http.post
向数据库添加数据。我有以下代码来执行此操作:

RestaurantIndexCtrl.js.coffee

restauranteur.controller 'RestaurantIndexCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) ->
$scope.restaurants = []
  $http.get('./restaurants.json').success((data) ->
    $scope.restaurants = data
  )
  $scope.addRestaurant = (test) ->
    $http({
      url: '/restaurants#create',
      method: "POST",
      data: JSON.stringify({name:test}),
      headers: {'Content-Type': 'application/json'}
    })

]
@restauranteur = angular.module('restauranteur', ['ngRoute'])

@restauranteur.config(['$routeProvider', ($routeProvider) ->
  $routeProvider
  .when('/restaurants', {
    templateUrl: '../templates/restaurants/index.html',
    controller: 'RestaurantIndexCtrl'
  })
    .otherwise({
        templateUrl: '../templates/home.html',
        controller: 'HomeCtrl'
      })
])
templates/restaurants/index.html

<form ng-submit="addRestaurant(restaurant.name)">
    <input type="text" ng-model="restaurant.name">
    <button>Register</button>
</form>
<ul ng-repeat="restaurant in restaurants">
    <li><a ng-click="viewRestaurant(restaurant.id)">{{ restaurant.name }}</a></li>
</ul>
现在,当我完成
textfield
并将数据发布到rails项目时,在刷新页面之前,数据不会添加到数据库中。当我刷新时,数据被添加到数据库中,并在
index.html
上显示数据

  • 我希望当我通过angularjs复制
    textfield
    并发布到rails控制器时,新数据被添加到数据库并显示在
    index.html
    上,而无需重新编辑。我该怎么做?问题存在于rails控制器或angularjs代码中

  • 我为
    餐厅名称
    设置了
    唯一验证
    ,现在如果我发送数据库中存在的名称,rails控制器不允许向数据库添加数据。如何获取rails在
    angularjs
    html代码中生成并向用户显示的错误

  • Note
    :我对angularjs使用外部视图,将模板放入
    public
    文件夹中,然后通过
    ngRoute
    路由url

    main.js.coffee

    restauranteur.controller 'RestaurantIndexCtrl', ['$scope', '$location', '$http', ($scope, $location, $http) ->
    $scope.restaurants = []
      $http.get('./restaurants.json').success((data) ->
        $scope.restaurants = data
      )
      $scope.addRestaurant = (test) ->
        $http({
          url: '/restaurants#create',
          method: "POST",
          data: JSON.stringify({name:test}),
          headers: {'Content-Type': 'application/json'}
        })
    
    ]
    
    @restauranteur = angular.module('restauranteur', ['ngRoute'])
    
    @restauranteur.config(['$routeProvider', ($routeProvider) ->
      $routeProvider
      .when('/restaurants', {
        templateUrl: '../templates/restaurants/index.html',
        controller: 'RestaurantIndexCtrl'
      })
        .otherwise({
            templateUrl: '../templates/home.html',
            controller: 'HomeCtrl'
          })
    ])
    

    一种方法是让您的
    create
    方法返回更新后的
    @restaurants
    ,然后在角度侧的回调中更新范围。真正的粗略实施:

    def create
        @restaurant = Restaurant.new(restaurant_params)
    
        if @restaurant.save
          render json: Restaurant.all, status: 200
        else
          #whatever
        end
      end
    end
    
    在前端:

    $scope.addRestaurant = function(test) {
      var data = {name: test}
      $http.post('/restaurants', data).success(function(data){
        $scope.restaurants = data;
      })
    }
    
    避免往返服务器的另一种方法是假设成功,并将新对象推送到客户端现有的
    $scope.restaurants
    。由于您的验证,这会带来一些问题

    对于验证,错误已在控制器中呈现:

    format.json { render json: @restaurant.errors, status: :unprocessable_entity }
    
    您必须将
    .error
    处理程序添加到
    $http
    调用中,并在
    $scope.errors
    或向用户显示的内容中设置返回的数据


    您可能还希望将api调用抽象到angular服务中,以便可以在应用程序的其他部分重用代码。也可以考虑读取<代码>解析> <代码> > $RouTePvices < /代码>,并在视图加载之前使用它来解析您的数据。

    我使用您的指南,但是当我将数据发送到数据库并保存数据时,我得到这个错误:<代码>完成406,在114MS中不可接受。(ActionController::UnknownFormat):app/controller/restaurants\u controller.rb:32:in create。对,您可能需要使用数据格式。有关错误的详细信息,请查看服务器日志。它可能类似于
    var data={restaurant:{name:test}
    数据是正确的,因为新餐厅正确地添加到数据库中。但我不知道
    已完成406不可接受的问题
    。数据在保存到数据库后不会发送到angularjs,直到我再次重新加载页面。如果是语法错误,请参阅我的编辑以了解控制器中的创建操作。没错,但当我向数据库添加数据时,我只需在视图中显示最新记录并
    呈现json:Restaurant.all,status:200
    不工作,如果工作,数据不会从rails控制器发送到angularjs控制器。您知道原因吗?