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