1

Rails 3.2 アプリ内のいくつかのフォームを AngularJS を使用するように変換して、ライブ計算などを実行できるようにしています。私の Rails アプリでは、money-railsを使用して通貨を処理しています。これは、すべての通貨フィールドをセントで構成される整数として扱います。

これは、すべての情報を JSON 経由で AngularJS テンプレートに送信するときに問題になります。今では、フォームをドルとセントで表示したいときに、すべてセントで表示されています。

AngularJSコントローラーに変換を入れたので、サーバーからデータを取得すると、更新する直前にセントからドルとセントに、またはその逆に変換します。コードは次のとおりです。

# Edit Investor
window.InvestorEditCtrl = ($scope, $routeParams, $location, Investor, Common) ->
  console.log 'InvestorEditCtrl'

  # Setup variable for common services(factory)
  $scope.common = Common

  $scope.master = {}  # Initialise our main object hash
  investor_id = $routeParams.investor_id   # Get the ID of the investor we are editing from the URL

  # Get the investor information & assign it to the scope master object
  console.log 'Get JSON'
  $scope.investor = new Investor.show({investor_id: investor_id}, (resource) ->
    # copy the response from server response (JSON format) to the scopes master
    $scope.master = angular.copy(resource)

    # Convert price_cents to dollars
    $scope.investor.price_cents /= 100
  )

  # Update the investor passing the JSON back to the server.    
  $scope.update = (investor) ->

    # Convert price_cents to cents
    investor.price_cents *= 100

    $scope.master = angular.copy(investor)

    investor.$update({investor_id: investor_id}, (t) ->
      $location.path('/investors/' + t.id)
    )

これを行うより良い方法はありますか?

4

1 に答える 1

1

HTML で必要な形式に変換するフィルターまたはディレクティブを作成できます。フィルターは次のようになります。

app.filter('centsToDollars', function() {
  return function(input) {
    var out = input / 100;
    return out;
  }
});

次に、HTML で、ドルとセントをセントで表示したい場所に、次のように呼び出します。

<p>{{investor.price_cents | centsToDollars}}</p>

フィルターはデータの表示にのみ影響し、基になるデータがセントから変更されることはありません。

入力フィールドの表示を変更する必要がある場合は、おそらくディレクティブの方が適しています。ここで参照されているようなことを行うことができます

app.directive('myCentsToDollars', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      var toDollars = function(text) {
        var text = (text || "0");
        return (parseFloat(text) / 100);
      }
      var toCents = function(text) {
        var text = (text || "0");
        return (parseFloat(text) * 100);
      }

      ngModel.$parsers.push(toDollars);
      ngModel.$formatters.push(toCents);
    }
  }
});

次に、html で次のようにします。

<input type="text" my-cents-to-dollars ng-model="investor.price_cents" />
于 2013-02-05T18:29:03.137 に答える