Angular.js integration with Ruby On Rails Forms

Using angular.js often items like ng-click or ng-model are written directly in the html form element like so....

<input type="text" ng-model="name">

How would I do that with rails? As rails uses embedded ruby and generates the html....

<%= form_for(@user) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>

How would I add the ng-model to <%= f.text_field :name %> ?

Ideally, you don't want to be mixing embedded ruby interpolation and Angular's interpolation. It's better to have ruby asynchronously serve JSON to Angular, and let Angular take care of filling in the data on the client side.

Try this, when it's a hyphen separated word, you need to put within a hash notation.

f.text_field :name, :ng => {:model => "name"}

I was working with AngularJS directives and Rails 4 in order to make the bootstrap-datepicker jquery plugin work on a Rails 4 erb template, the code that I used inside the text_field_tag is the following:

<%= text_field_tag(:start_day, nil, class: 'form-control', datepicker: 'datepicker') %>  

It's important to notice that this works with AngularJS directives, the code that you get on the DOM is as follows:

<input class="form-control" datepicker="datepicker" type="text">

I worked with the directive in the following way:

timeAdminCal.directive('datepicker', function(){
      return {
        restrict: 'A',
        link: function ($scope, $element) {
          $element.datepicker({
            format: 'd/m/yyyy',
            autoclose: true,
            todayHighlight: true
          });
        }
      }
    });

Notice that, according to AngularJS directive docs you can restrict a class name, so you may use any class name on your text_field_tag and it will work too.

timeAdminCal.directive('datepicker', function(){
      return {
        restrict: 'C', // Bind DOM element by class name 'datepicker'
        link: function ($scope, $element) {
          $element.datepicker({
            format: 'd/m/yyyy',
            autoclose: true,
            todayHighlight: true
          });
        }
      }
    });

The following is what worked for me (But it will disable error message("Please enter name.") of angularjs, i.e. required: "required"):

<%= f.input :id, as: :select, label: false, prompt: 'Select a selection',  input_html: { "ng-model" => ""} %>

I think you can use the :html option to set any element attributes. Haven't tried it with angular.js special attributes though ;-)

f.text_field :name, :html => { :ng-model => "name" }

On my current project, I had to start transforming static templates into angular pages, what I did was to render jbuilder views inside the template and put it in ng-init.

If the screen ever becomes part of a single page app, I will simply have to remove that render and add a query to the api to load that data. That's how Twitter does it, and it's simple and effective.