What’s the best way to show and get input from text field, only when "Others" is selected on select box?

I’m using Ruby on Rails and AngularJS, and currently I’m using Angular to show the text field depending on selection. However, I’m having trouble with saving the value.

My 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'"

My js.erb:

$("document").ready(function() {
  formApp = angular.module('formApp', []);
  formApp.controller('TypeCtrl', ['$scope', function($scope) {
    $scope.init = function(type) {
      $scope.type_select = type;
    }
  }]);
});

@type used in ng-init is defined in my controller. Currently, I’ve got the dropdown to display correctly on init, and it shows the text field as expected. However, it’s always saving the type field as whatever is typed in, instead of looking at dropdown (probably because I have 2 input fields both for type). What is the conventional way to fix this with RoR and AngularJS?


Source: ruby

Leave a Reply