Search code examples
angularjsangularjs-scopenanangularjs-controller

AngularJs: How to initialize the value for function Which is returning NaN?


I had a problem on my code in angularJs function which is return NaN instead of 0 during initialization.

Sample Code is Here

var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
    
    
    $scope.finalNo = function(firstNo,secondNo) {
        
        var amount = firstNo*1 + secondNo*1;
        return amount;
    };
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">

First No: <input type="text" ng-model="firstNo"><br>
Second No: <input type="text" ng-model="secondNo"><br>
<br>
<label ng-init="fullName(firstName,lastName) == 1 ">Final No: {{finalNo(firstNo,secondNo)}}</label>

</div>
  </body>
</html>

After you enter the firstNo and SecondNo, the finalNo displays the addition of 2 numbers. My problem is its initialized from NaN instead of 0. How to initialize from 0, also how to handle the NaN (ie,) in case of NaN, i want the value 0.

Thanks in advance.


Solution

  • Parse it using .parseInt() and at the initial level models are not initialized so it will always return calculations resulting not a number (NaN), to avoid it return amount || 0

    Hope this will help

    var app = angular.module('myApp', []);
    app.controller('personCtrl', function($scope) {
        $scope.finalNo = function(firstNo,secondNo) {
            
            var amount = parseInt(firstNo) * 1 + parseInt(secondNo) * 1;
            return amount || 0;
        };
    });
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="personCtrl">
    
    First No: <input type="text" ng-model="firstNo"><br>
    Second No: <input type="text" ng-model="secondNo"><br>
    <br>
    <label>Final No: {{finalNo(firstNo,secondNo)}}</label>
    
    </div>
      </body>
    </html>