Math functions in AngularJS bindings

后端 未结 13 1164
无人及你
无人及你 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:28

    This is more or less a summary of three answers (by Sara Inés Calderón, klaxon and Gothburz), but as they all added something important, I consider it worth joining the solutions and adding some more explanation.

    Considering your example, you can do calculations in your template using:

    {{ 100 * (count/total) }}
    

    However, this may result in a whole lot of decimal places, so using filters is a good way to go:

    {{ 100 * (count/total) | number }}
    

    By default, the number filter will leave up to three fractional digits, this is where the fractionSize argument comes in quite handy ({{ 100 * (count/total) | number:fractionSize }}), which in your case would be:

    {{ 100 * (count/total) | number:0 }}
    

    This will also round the result already:

    angular.module('numberFilterExample', [])
      .controller('ExampleController', ['$scope',
        function($scope) {
          $scope.val = 1234.56789;
        }
      ]);
    
    
        
        
      
      
        
    No formatting: {{ val }}
    3 Decimal places: {{ val | number }} (default)
    2 Decimal places: {{ val | number:2 }}
    No fractions: {{ val | number:0 }} (rounded)

    Last thing to mention, if you rely on an external data source, it probably is good practise to provide a proper fallback value (otherwise you may see NaN or nothing on your site):

    {{ (100 * (count/total) | number:0) || 0 }}
    

    Sidenote: Depending on your specifications, you may even be able to be more precise with your fallbacks/define fallbacks on lower levels already (e.g. {{(100 * (count || 10)/ (total || 100) | number:2)}}). Though, this may not not always make sense..

提交回复
热议问题