我正在使用 Ruby on Rails 和 AngularJS,目前我正在使用 Angular 根据选择显示文本字段。但是,我在保存该值时遇到了问题。
我的 html.haml:
%div{ "ng-app" => "formApp" }
= simple_form_for(@app) do |f|
.form-group{ "ng-controller" => "TypeCtrl", "ng-init" => "init('#{@type}')" }
= f.label :type, "Type"
= f.select :type, type_selection, { }, { required: true, class: "form-control", "ng-model" => "type_select" }
= f.text_field :type, class: "form-control", "ng-show" => "type_select=='others'"
我的js.erb:
$("document").ready(function() {
formApp = angular.module('formApp', []);
formApp.controller('TypeCtrl', ['$scope', function($scope) {
$scope.init = function(type) {
$scope.type_select = type;
}
}]);
});
ng-init
中使用的 @type
是在我的 Controller 中定义的。目前,我已经在 init 上正确显示了下拉列表,并且它按预期显示了文本字段。但是,它总是将 type
字段保存为输入的内容,而不是查看下拉列表(可能是因为我有 2 个 type
输入字段)。使用 RoR 和 AngularJS 解决此问题的传统方法是什么?
最佳答案
您不应该有多个同名的输入。它会分配最后一个。考虑将其更改为例如type_select
和另一个 type_input
然后在 Controller 端单独处理它们。
Rails
示例:
if params[:type_select] == 'Other'
type = params[:type_input]
else
type = params[:type_select]
end
关于javascript - 仅当在选择框中选择 "Others"时,显示文本字段并获取输入的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31110898/