2013-02-05 27 views
1

我正在轉換我的Rails 3.2應用程序內的一些表單以使用AngularJS,以便我可以進行實時計算等。在我的Rails應用程序中,我使用money-rails來處理貨幣。這將所有貨幣字段視爲由美分組成的整數。與AngularJS使用錢軌

當我通過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) 
    ) 

有沒有更好的方法來做到這一點?

回答

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