Why Math.floor return nothing when we write it into HTML angular?

All we need is an easy explanation of the problem, so here it is.

Here is my HTML:

<div ng-controller = "myCntrl">  
    <pre>floor 1: {{Math.floor( value )  }}</pre>  
    <pre>floor 2: {{value }}</pre>  
    <pre>floor 3: {{value | number : 0 }}</pre>  
    <pre>floor 1 from controller: {{newValue }}</pre>  


app.controller('myCntrl', function ($scope) {
    $scope.value = 1233.8435;
    $scope.newValue = Math.floor(1233.8435);    

The output:

floor 1: 
floor 2: 1233.8435
floor 3: 1,234
floor 1 from controller: 1233

Generally I’m looking for the proper way to get 1233.

I don’t want to invoke new method in controller.

Why Math.floor returns nothing?


Demo Fiddle

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In this case, AngularJS <span>{{value}}</span> (expression) is shorthand for <span ng-bind="value"></span> and ng-bind acts on the current scope.

Your current scope is the one defined by myCntrl so ng-bind="value" is evaluated as $scope.value.

AngularJS has no way of making a distinction between the global Math namespace and $scope.Math, so it treats it like any other scoped expression.

I’d advise against using $scope.Math=Math;.

The correct way to do it is using a filter:

angular.module('myApp',[]).filter('floor', function(){

    return function(n){
        return Math.floor(n);

Method 2

Expressions are evaluated on the $scope. If you do this in your controller


it would work.

Method 3

Put it in your controller

<div ng-controller = "myCntrl">  
  <pre>floor 1: {{Mathvalue}}</pre>  
  <pre>floor 2: {{value }}</pre>  
  <pre>floor 3: {{value | number : 0 }}</pre>  

var app = angular.module('myModule', []);

app.controller('myCntrl', function ($scope) {
  $scope.value = 1233.8435; 
  $scope.Mathvalue = Math.floor(1233.8435);

app.$inject = ['$scope'];

Method 4

Angular expression doesn’t support all javascript method, for example Math.floor(), you can declear a floor function on your $scope and delegete Meth floor

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply