How to parseInt in Angular.js
Probably, it is the simplest thing but I couldn't parse a string to Int in angular..
What I am trying to do:
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">
Total: {{num1 + num2}}
How can I sum these num1 and num2 values?
Thnx!
Solution 1:
You cannot (at least at the moment) use parseInt
inside angular expressions, as they're not evaluated directly. Quoting the doc:
Angular does not use JavaScript's
eval()
to evaluate expressions. Instead Angular's$parse
service processes these expressions.Angular expressions do not have access to global variables like
window
,document
orlocation
. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.
So you can define a total()
method in your controller, then use it in the expression:
// ... somewhere in controller
$scope.total = function() {
return parseInt($scope.num1) + parseInt($scope.num2)
}
// ... in HTML
Total: {{ total() }}
Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with -0
op:
Total: {{num1-0 + (num2-0)|number}}
... but that'll obviously won't parseInt values, only cast them to Numbers (|number
filter prevents showing null
if this cast results in NaN
). So choose the approach that suits your particular case.
Solution 2:
Option 1 (via controller):
angular.controller('numCtrl', function($scope, $window) {
$scope.num = parseInt(num , 10);
}
Option 2 (via custom filter):
app.filter('num', function() {
return function(input) {
return parseInt(input, 10);
}
});
{{(num1 | num) + (num2 | num)}}
Option 3 (via expression):
Declare this first in your controller:
$scope.parseInt = parseInt;
Then:
{{parseInt(num1)+parseInt(num2)}}
Option 4 (from raina77ow)
{{(num1-0) + (num2-0)}}