3

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?

4

4 回答 4

16

在输出中添加“+”符号可以很简单:

{{number > 0 ? '+' : ''}}{{number}}

如果你需要到处做,我可能会写一个指令来附加符号。

注意: 三元运算符仅适用于 Angular 1.2+

http://jsfiddle.net/jwcarroll/NNgw6/

于 2013-11-14T02:00:56.173 回答
8

AngularJS 执行此操作的方法是通过自定义过滤器。过滤器用于格式化和显示数据。此外,它们可以很容易地在多个地方重复使用。有一个类似的帖子,其中包含一个如何使用自定义过滤器来解决格式问题的示例。

于 2013-11-14T07:03:09.050 回答
3

如果我在这里了解您的需求,您应该能够使用函数来获取数据,而不是直接访问整数。

app.controller('myCtrl', function($scope) {
  var foo = 1;
  $scope.getData = function() {
    if (foo > 0) {
       foo = '+'+parseInt(foo);
    }
    return foo;
  }
});

<p>{{getData()}}</p> <!-- displays "+1" -->

现场演示在这里。(点击)

于 2013-11-14T01:56:54.877 回答
1

您还可以使用“过滤器”方式:

app.filter('plusOrMinus', function(){
    return function(input){
        input = input ? input : 0
        return input > 0 ? "+"+input : input
    }
})

那么在你看来:

<p>{{number | plusOrMinus}}</p>
于 2016-09-19T20:19:05.373 回答