Marek123
Marek123

Reputation: 1211

AngularJS - Adding value to to value

Is it possible to add a integer to a scope variable?

e.g

<div style="top:{{top + 140}}px">....</div>  

If top is 140 it should give me "280px" and not "140140px"

Is this possible?

Upvotes: 3

Views: 2612

Answers (2)

Scott Sword
Scott Sword

Reputation: 4708

Regarding your response to @Mathew Berg:

The reason that you're running into this problem is because you are telling Angular that "top" is a string literal. While Mathew's method does the trick to interpret the value as an integer, it is still basically a workaround. @blesh is totally right in saying that you should be doing this at the controller level. So...

This

function myContoller($scope) {
    $scope.top = '1';
}
<div style="top:{{top + 140}}px"></div>
<!-- Output = <div style="top:1140px"></div> -->

and this

function myContoller($scope) {
    $scope.top = 'one';
}
<div style="top:{{top + 140}}px"></div>
<!-- Output = <div style="top:one140px"></div> -->

are handled in the same manner.

Basically you are inadvertiently concatenating instead of the intended arithmetic.

Forturnately the remedy is SUPER easy. All you need to do is remove the parenthesis from the integer that you are passing and then Angular will say "hey this is a number, lets do some math".

eg 
function myController($scope) {
    $scope.top = 140;
}

<div style="top:{{top + 140}}px"></div>
<!-- Output = <div style="280px"></div> -->

You stated "Top is in the $scope.dealer and I'm using an ng-repeat="d in dealer". so correctly it would be d.top" so you might have to tweak this a bit to access the proper scope, but the solution holds true nonetheless. One of the awesome things about Angular is that it can inherently handle expressions within it's markup syntax. Hopefully this will help explain what is causing your problem, because Angular DOES work the way you want it to, as it should. =)

Upvotes: 1

Mathew Berg
Mathew Berg

Reputation: 28750

Not that I think this is the best method, but you could try:

<div style="top:{{top * 1 + 140}}px">....</div>  

To force top to become an integer.

Upvotes: 4

Related Questions