Reputation: 3137
I need to show positive or negative number. The problem is that I get data from an api where I have a delta -X for positive and X for negative.
So to show my data I need to multiply per -1.
I have this code:
{{myData * -1}}
But I need a way to add a + symbol to my data in case it is positive. If I have (-120*-1) I should get +120.
How could I add plus to my number?
Upvotes: 3
Views: 14541
Reputation: 1569
You could also use the "filter" way:
app.filter('plusOrMinus', function(){
return function(input){
input = input ? input : 0
return input > 0 ? "+"+input : input
}
})
then on your view:
<p>{{number | plusOrMinus}}</p>
Upvotes: 1
Reputation: 845
The AngularJS way to do this is via a custom filter. Filters are used for formatting and displaying data. Moreover they can be easily reused in multiple places. There is a similar post with an example of a how a custom filter can be used to address a formatting problem.
Upvotes: 8
Reputation: 43755
If I understand your need here, you should be able to use a function to get the data rather than access the integer directly.
app.controller('myCtrl', function($scope) {
var foo = 1;
$scope.getData = function() {
if (foo > 0) {
foo = '+'+parseInt(foo);
}
return foo;
}
});
<p>{{getData()}}</p> <!-- displays "+1" -->
Upvotes: 3
Reputation: 44916
Adding a '+' symbol to your output could be as simple as this:
{{number > 0 ? '+' : ''}}{{number}}
If you need to do it all over the place, I would probably write a directive to append the symbol.
Note: The ternary operator will only work in Angular 1.2+
http://jsfiddle.net/jwcarroll/NNgw6/
Upvotes: 16