Math functions in AngularJS bindings

后端 未结 13 1187
无人及你
无人及你 2020-11-29 17:55

Is there a way to use math functions in AngularJS bindings?

e.g.

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

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 18:37

    Either bind the global Math object onto the scope (remember to use $window not window)

    $scope.abs = $window.Math.abs;
    

    Use the binding in your HTML:

    Distance from zero: {{abs(distance)}}


    Or create a filter for the specific Math function you're after:

    module.filter('abs', ['$window', function($window) {
      return function(n) {
        return $window.Math.abs($window.parseInt(n));
      };
    });
    

    Use the filter in your HTML:

    Distance from zero: {{distance | abs}}

提交回复
热议问题