Search code examples
ruby-on-railsangularjsrubyangularjs-directiverails-api

How to format currency input in RoR + AngularJS app


Sorry for my English.

I need to change input value format, for example: from "1000000" to "1 000 000 $".

In my views of rails app, I have this line of code:

<%= ng_text_field('total_price', 'selected.data.total_price', 'Full price', ng_readonly: '!selected.permissions.update') %>

In helper:

  def ng_text_field(name, ng_model, placeholder, options = {})
    result = <<-HTML
      <div class="form-group" ng-class='{"has-error":errors.#{name}}' #{options[:ng_if] && "ng-if=\"#{options[:ng_if]}\""}>
        <label for="#{name}" class="col-sm-3 control-label">#{placeholder}</label>
        <div class="col-sm-9">
          <input id="#{name}" 
                 type="text" 
                 class="form-control" 
                 name="#{name}" 
                 placeholder="#{placeholder}" 
                 ng-model="#{ng_model}"
                 #{options[:ng_readonly] && "ng-readonly=\"#{options[:ng_readonly]}\""}>
          <p class="help-block small" ng-if="errors.#{name}">{{errors.#{name} | join:',' }}</p>
        </div>
      </div>
    HTML
    result.html_safe
  end

I am know Angular very little, I have tried some ways and all this ways was incorrect. :(

Could anyone give advice of some help? Thank you in advance


Solution

  • You're going to need to create a new directive that requires ngModel and applies the appropriate $parser/$formatter to it.

    https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$parsers

    A good example of how to do this is (displaying as uppercase but always storing data as lowercase):

    ngModel Formatters and Parsers

    You should be able to then add the ability to include other directives in your 'options' argument so that they get added correctly to the output.