【问题标题】:What's the best way to show and get input from text field, only when "Others" is selected on select box?仅当在选择框中选择“其他”时,显示和从文本字段获取输入的最佳方式是什么?
【发布时间】:2015-06-29 08:19:30
【问题描述】:

我正在使用 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 在我的控制器中定义。目前,我已经让下拉菜单在 init 上正确显示,并按预期显示文本字段。但是,它总是将type 字段保存为输入的任何内容,而不是查看下拉列表(可能是因为我有两个type 的输入字段)。使用 RoR 和 AngularJS 解决此问题的常规方法是什么?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby angularjs


    【解决方案1】:

    您不应该有多个具有相同名称的输入。它将分配最后一个。考虑将一个更改为例如type_select 和另一个 type_input 然后在控制器端单独处理它们。

    Rails 示例:

    if params[:type_select] == 'Other'
      type = params[:type_input]
    else
      type = params[:type_select]
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-09-12
      相关资源
      最近更新 更多