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

如。

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

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

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


当前回答

这看起来不像是一种非常Angular的方式。我不完全确定为什么它不起作用,但您可能需要访问作用域才能使用这样的函数。

我的建议是创建一个过滤器。这就是Angular的方式。

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

然后在你的HTML中这样做:

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

其他回答

你必须将Math注入你的作用域,如果你需要使用它 $scope对数学一无所知。

你可以用最简单的方法

$scope.Math = window.Math;

在控制器中。 Angular的正确方法是创建一个Math服务。

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

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

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

使用管道的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'}}

这看起来不像是一种非常Angular的方式。我不完全确定为什么它不起作用,但您可能需要访问作用域才能使用这样的函数。

我的建议是创建一个过滤器。这就是Angular的方式。

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

然后在你的HTML中这样做:

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

更好的选择是使用:

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

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