Reputation: 878
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?
Upvotes: 1
Views: 41
Reputation: 2390
You shouldn't have multiple inputs with the same name. It'll assign the last one. Consider changing one to e.g. type_select
and the other to type_input
then handle them individually on the controller side.
Rails
example:
if params[:type_select] == 'Other'
type = params[:type_input]
else
type = params[:type_select]
end
Upvotes: 1