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;
};
});
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]);
};
...
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?