Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding angular directives to simple_form in rails breaks selected option for collection input

Not sure if there's a workaround for this, I'm doing something wrong, or this is a collision between simple form or angular, but:

.field
  = f.input :role, collection: roles.map(&:name), selected: user.role.try(:name), include_blank: 'Select', required: true, input_html: { "ng-model" => "role" }

renders (which looks correct):

   <select ng-model="role" class="select required" name="user[role]" id="user_role">
      <option value="">Select</option>
      <option value="system">system</option>
      <option selected="selected" value="fcm">fcm</option>
      <option value="regulatory">regulatory</option>
      <option value="operations">operations</option>
      <option value="help_desk">help_desk</option>
     </select>

But the selected value is the include_blank value of 'Select'. And yes, role is set on the user.

like image 696
daino3 Avatar asked Dec 01 '15 23:12

daino3


1 Answers

The reason it's doing this is because of the way angular models work and it requires an understanding of this. Essentially the ruby generates the select correctly choosing the selected option of the select box too.

However, once the angular is loaded and sees ng-model on this select it sets the current selected option to the value of the model, in your case, role.

Thus if you want to have an angular model for this select, you need to set the initial value of that model.

Try the following:

.field
= f.input :role, collection: roles.map(&:name), include_blank: 'Select', required: true, input_html: { "ng-model" => "role", "ng-init" => "role = #{user.role.try(:name)}" }

Note that the selected option has been removed entirely since this will be controlled by the Angular model, which is initialized to that value using ruby string interpolation.

like image 183
Guy Avatar answered Sep 19 '22 00:09

Guy