Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating sum using Angular

I'm beginner on AngularJs and I have a difficult to show the sum of two numbers. The first script work perfectly :

<div>
   <p><input type="text" ng-model="price1" /> <strong>{{price1}}</strong></p>
   <p><input type="text" ng-model="price2" /> <strong>{{price2}}</strong></p>
   <p><strong>{{total = (price1 * 1 + price2 * 1) }}</strong></p>
</div>

But when I try to test this using a controller, like this :

<div ng-controller="myCtrl">
   <p><input type="text" ng-model="price1" /> <strong>{{price1}}</strong></p>
   <p><input type="text" ng-model="price2" /> <strong>{{price2}}</strong></p>
   <p><strong>{{total}}</strong></p>
</div>
<script>
   var app = angular.module('firstApp', []);
   app.controller('myCtrl', ['$scope', function($scope) {
      $scope.total = ($scope.price1  + $scope.price2);
   }]);
</script>

I have no result, just a NaN value. I have no idea what happen !

like image 468
Med Avatar asked Jun 11 '26 06:06

Med


1 Answers

There are several issues in your code:

  1. The variables $scope.price1 and $scope.price2 are not defined once the controller is initialized. Arithmetical operation using undefined value produces NaN as the result.
  2. You compute the $scope.total just once. Its result is not updated on change of $scope.price1 or $scope.price2
  3. In the inputs you should use type="number" not type="text" then the values of $scope.price1 and $scope.price2 will be parsed and summed up as numbers. In your code they are concatenated as strings.

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

app.controller("myCtrl", function ($scope) {
  $scope.price1 = 1;
  $scope.price2 = 2;
  
  $scope.getTotal = function() {
    return $scope.price1 + $scope.price2;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
   <p><input type="number" ng-model="price1" /> <strong>{{price1}}</strong></p>
   <p><input type="number" ng-model="price2" /> <strong>{{price2}}</strong></p>
   <p><strong>{{getTotal()}}</strong></p>
</div>
</div>
like image 119
Alexander Elgin Avatar answered Jun 13 '26 20:06

Alexander Elgin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!