8

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>  
</div>

Controller

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?

Thanks,

Demo Fiddle

snaggs
  • 5,543
  • 17
  • 64
  • 127

4 Answers4

19

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);
    };
});
Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
13

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

$scope.Math=Math;

it would work.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
1

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>  
</div>

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

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

app.$inject = ['$scope'];
fauverism
  • 1,970
  • 3
  • 33
  • 59
0

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

Sean
  • 2,990
  • 1
  • 21
  • 31