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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With