【问题标题】:Using money-rails with AngularJS在 AngularJS 中使用 money-rails
【发布时间】:2013-01-19 22:44:39
【问题描述】:

我正在将我的 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)
    )

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: ruby-on-rails angularjs


    【解决方案1】:

    您可以编写过滤器或指令,将其转换为您想要的 HTML 格式。过滤器看起来像这样:

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

    然后,在您的 html 中,无论您希望在哪里显示美分和美分,都可以这样称呼它:

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

    过滤器只会影响数据的显示,不会修改底层数据为美分。

    如果您需要修改输入字段的显示,更好的路由可能是指令。你可以做类似here

    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" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      • 2014-07-22
      相关资源
      最近更新 更多