[angularjs] 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!

This question is related to angularjs

The answer is


var app = angular.module('myApp', [])

app.controller('MainCtrl', ['$scope', function($scope){
   $scope.num1 = 1;
   $scope.num2 = 1;
   $scope.total = parseInt($scope.num1 + $scope.num2);

}]);

Demo: parseInt with AngularJS


<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">

Total: {{num1 + num2}}

and in js :

parseInt($scope.num1) + parseInt($scope.num2)

This are to way to bind add too numbers

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
  return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


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)}}

Inside template this working finely.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
<input ng-model="name" value="0">
<p>My first expression: {{ (name-0) + 5 }}</p>
</div>

</body>
</html>

Perform the operation inside the scope itself.

<script>
angular.controller('MyCtrl', function($scope, $window) {
$scope.num1= 0;
$scope.num2= 1;


  $scope.total = $scope.num1 + $scope.num2;

 });
</script>
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">

Total: {{total}}