Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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. AngularJs: Input model changes from Integer to String when changed

share|improve this answer
    
Thanks a lot! I totally forgot about this field type, I guess I am still reluctant to use HTML5 new elements. The code with directive is what I was looking for too, will definitely use that for some type conversions. –  user3477668 Mar 30 '14 at 22:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.