AngularJS中的嵌套表单字段

时间:2014-12-17 13:55:49

标签: ruby-on-rails json angularjs nested-forms

我正在开发一个带有远程Rails后端的AngularJS应用程序,用于体育赛事的注册。除了注册为单一跑步者之外,用户还应该能够为4名参赛者提交接力队的注册。

Rails后端结构:

class Relay < ActiveRecord::Base
  has_many :registrations
  accepts_nested_attributes_for :registrations
end

class Registration < ActiveRecord::Base
  belongs_to :relay
end

class API::RelaysController < API::BaseController
  def create
    @relay = Relay.new(relay_params)
    if @relay.save
      render json: @relay, status: :created#, location: @relay
    else
      render json: @relay.errors, status: :unprocessable_entity
    end
  end
end

Rails 前端中的嵌套表单:

Nested form in Rails frontend

My Angular relay创建控制器:

appControllers.controller('RelayCreateCtrl', ['$scope', '$routeParams', 'Relay', 'Registration', '$location', function($scope, $routeParams, Relay, Registration, $location) {
  $scope.errors = {}
  $scope.relay = new Relay();

  $scope.registrations_attributes = [];
  for (var i=0; i<4; ++i ){
    registration = new Registration();
    registration.run_id = $routeParams.run_id;
    $scope.registrations_attributes.push(registration);
  }    
  $scope.relay.registrations_attributes = $scope.registrations_attributes;
  $scope.submit = function() {
    function success(response) {
      console.log("success", response)
      $location.path("/registrations");
    }

    function failure(response) {
      console.log("failure", response);
      $scope.errors = response.data;
      console.log($scope.errors);
    }

    Relay.create($scope.relay, success, failure)
  };
}]);

ngResource Services:

rilaServices.factory('Registration', ['$resource',
  function($resource){
    return $resource('http://localhost:3000/api/registrations/:id', { id: "@id" }, {
      'create':  { method: 'POST' }
    });
  }
 ]);

rilaServices.factory('Relay', ['$resource',
  function($resource){
    return $resource('http://localhost:3000/api/relays/:id', { id: "@id" }, {
      'create':  { method: 'POST' }
    });
  }
 ]);

中继create.html上:

<form name="form" ng-submit="submit()" class="form-horizontal" novalidate>
  <div ng-repeat="registration in relay.registrations_attributes" ng-form="registration_form" class="well">
    ...
    <div class="form-group">
      <label class="control-label col-sm-4">
        Firstname
      </label>
      <div class="input-group col-sm-7">
        <input class="form-control" ng-model="registrations_attributes.runner_firstname" type="text">
      </div>
    </div>
    ...
  </div>
</form>

我需要遵循哪些步骤来获取在AngularJS中运行的嵌套字段的表单,就像我在Rails中创建的那样?

0 个答案:

没有答案