有没有办法在AngularJS绑定中使用数学函数?

如。

<p>The percentage is {{Math.round(100*count/total)}}%</p>

这把小提琴说明了这个问题

http://jsfiddle.net/ricick/jtA99/1/


当前回答

我认为最好的方法是创建一个过滤器,就像这样:

myModule.filter('ceil', function() {
    return function(input) {
        return Math.ceil(input);
    };
});

然后标记看起来像这样:

<p>The percentage is {{ (100*count/total) | ceil }}%</p>

更新小提琴:http://jsfiddle.net/BB4T4/

其他回答

数字过滤器使用数千个分隔符格式化数字,因此它不是严格意义上的数学函数。

此外,它的小数“限制器”并没有限制任何小数(正如其他一些答案会让你相信的那样),而是四舍五入。

因此,对于任何你想要的数学函数,你可以像这样注入它(模仿比注入整个math对象更容易):

myModule.filter('ceil', function () {
  return Math.ceil;
});

也不需要将它包装在另一个函数中。

使用管道的Angular Typescript示例。

math.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'math',
})

export class MathPipe implements PipeTransform {

  transform(value: number, args: any = null):any {
      if(value) {
        return Math[args](value);
      }
      return 0;
  }
}

添加到@NgModule声明中

@NgModule({
  declarations: [
    MathPipe,

然后在模板中像这样使用:

{{(100*count/total) | math:'round'}}

虽然公认的答案是正确的,你可以注入Math来在angular中使用它,对于这个特定的问题,更传统的/angular方式是数字过滤器:

<p>The percentage is {{(100*count/total)| number:0}}%</p>

你可以在这里阅读更多关于数字过滤器的信息:http://docs.angularjs.org/api/ng/filter/number

使用Angular进行简单计算的最简单方法是根据需要直接在HTML标记中进行单个绑定,假设你不需要在页面上进行大量计算。这里有一个例子:

{{(data.input/data.input2)| number}} 

在本例中,您只需在()中进行数学运算,然后使用筛选器|来获得数字答案。这里有更多关于将Angular数字格式化为文本的信息:

https://docs.angularjs.org/api/ng/filter

更好的选择是使用:

{{(100*score/questionCounter) || 0 | number:0}}

在值未初始化的情况下,它将方程的默认值设置为0。