Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding numbers in Angular js

I'm learning angular js and got stuck in the following code:

<div ng-app="calculate">
Amount: <input type='text'  data-ng-model='amount' name = 'amount' placeholder = 'Enter amount' >
Charge: <input type='text'  name = 'charge' ng-bind="charge" value="{{ amount | serviceFilter }}" >
Total:  <input type='text'  value= " {{(amount)+ (amount | serviceFilter)}}" name = 'total' >
</div>

<script>
  angular.module('calculate', [])
  .filter('serviceFilter', function( ){
    return function(amount){
      if(angular.isUndefined(amount)){
        charge = '0';
      }else{
        if(isNaN(amount)){
          charge = 'Invalid Data !!!';
        }else{
          if(amount < 1000){
            charge = '200';
          }else{
            charge = '500';
          }
        }
      }
      return charge;
   };
  });
</script>

When I enter the amount. I get appropriate charge. But I can't add the amount and charge get the total value. Let's say:

Amount: 1200
Charge: 500
Total : 1700

I need to get 1700 but instead I get

Total: 1200 500

Also I want to know if this is the appropriate way or there is any other better way to do this. Thankyou

like image 746
nasor Avatar asked Jan 24 '26 00:01

nasor


1 Answers

This happens because when you bind the numbers in to text inputs they are treated as strings so change the text box type to number.

<input type='number' data-ng-model='amount' name='amount' placeholder='Enter amount'>

and change the string type numbers in filter to int

 app.filter('serviceFilter', function( ){
    return function(amount){      
      if(angular.isUndefined(amount)){
        charge = 0;
      }else{
        if(isNaN(amount)){
          charge = 'Invalid Data !!!';
        }else{
           if(amount < 1000){
             charge = 200;
          }else{
            charge = 500;
          }
        }
      }
      return charge;
   };
});

or return the charge after converting to int return parseInt(charge); like @LVarayut suggested.

here is the Demo Plunker


OR

do a simple hack to convert these string values to int as,

 <input type='text' value="{{ (amount-0) + ((amount | serviceFilter)-0) }}" name='total'>

(amount-0) and ((amount | serviceFilter)-0) will return a int, removing 0 will result in a number.

here is the Demo Plunker

like image 194
Kalhan.Toress Avatar answered Jan 26 '26 13:01

Kalhan.Toress