How to parseInt in Angular.js

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 or location. 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.

Leave a Comment