Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parseInt in Angular.js

Tags:

angularjs

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!

like image 818
Mar Avatar asked Sep 09 '25 15:09

Mar


1 Answers

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.

like image 157
raina77ow Avatar answered Sep 12 '25 06:09

raina77ow