0

is it possible to convert String to int inside ng-click?

I have this data

$scope.cartList = [{ number: "1"}];

So in my view i just call number using ng-repeat( ng-repeat="cart in cartList"). I use number for increment by using ng-click.

<button data-ng-click="increment = 0 + cart.number></button>
<span>{{increment}}</span>

So here I got problem during calculation, I know cart.number is String but is there any way to convert cart.number to int inside ng-click?

2 Answers 2

2

Your logic is wrong . you are calculated with 0, it can't increase the count . So you should calculate with latest increment value instead of 0.

Try this

<button data-ng-click="increment = increment + parseInt(cart.number)"></button>
<span>{{increment}}</span>

Please assign parseInt in a scope object in controller. then use that in button

$scope.parseInt = parseInt;

You can check the demo here:

angular.module("app",[])
function Homecontroller($scope)
{
$scope.cartList = [{ number: "1"}];
$scope.parseInt=parseInt;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Homecontroller">
<button data-ng-click="increment = increment + parseInt(cartList[0].number)">increase</button>
<span>{{increment}}</span>
 </div>

Sign up to request clarification or add additional context in comments.

7 Comments

then? I already try to use this Number(cart.number) as advice by Saurabh. but still not working
ahh ok2, but I have update my code but cart.number is still String. Number(cart.number) not convert String to int
still not working man. the {{increment}} still not increase
It's working to me. added code on snippet. check it now
app.filter('numb', function() { return function(input) { return parseInt(input, 10); }; }); is this still using? seams like you are not using numb in view button
|
0

parseInt is used to convert string to int but it cannot be used inside angular expression. So, you can create a function which converts your string to an integer value and then do the desired computation.

In your controller:

$scope.doIncrement = function(cartNumber) { 
  $scope.increment = 0 + parseInt(cartNumber); 
}

In your view:

<button ng-click="doIncrement(cart.number)"></button>
<span>{{increment}}</span>

2 Comments

well I think he wants to do it in view only, Not in controller.
yes I know, just try my luck. I don't want to do it in controller, because my project now most of calculation in view for some reason. is there any way how to convert number to int ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.