문제

I am trying to build an app for calculating tax using angular.js as a tutotrial for me to understand the framework. First thing I noticed is that user input is by default assumed to be string, which obviously makes sum function a string concatenation instead of numerical operation, see here:

var taxApp = angular.module('taxApp', []);

taxApp.controller('taxController', function($scope) {

    $scope.user_data = {
      income_1: 0.00,
      income_2: 0.00
    };

    $scope.total = function() {
      return $scope.user_data.income_1 + $scope.user_data.income_2;
    };


});

http://jsfiddle.net/96beZ/3/

I could add parseFloat for each attribute but the thing is my app will eventually have about 10-20 user input fields and between 5-10 calculations. I want to avoid having multiple repetitions of parseFLoat all over the place in controller code. So far, I only got something like that using ng-change:

...
$scope.parseFLoat = function(model) {
  $scope.user_data[model] = parseFloat($scope.user_data[model]);
};
...

http://jsfiddle.net/96beZ/5/

The thing I don't like though is that I still need to pass the variable name so this is too model name dependent.

Is there a smarter way to achieve what I want, perhaps using directives? Or maybe Angular has an in-built function for changing value types?

도움이 되었습니까?

해결책

Change the input type to number

<label for="income-1">Income 1</label>
<input type="number" id="income-1" ng-model="user_data.income_1" />
<label for="income-2">Income 2</label>
<input type="number" id="income-2" ng-model="user_data.income_2" />

and it will convert to numbers automatically.

In a more complex situation (for example you need input type to be text for some reason), you can easily build directives to take care of the conversion, see e.g. Input model changes from Integer to String when changed

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top