Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 483
snaggs Avatar asked Nov 25 '13 15:11

snaggs


3 Answers

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);
    };
});
like image 151
Sergiu Paraschiv Avatar answered Nov 10 '22 04:11

Sergiu Paraschiv


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

$scope.Math=Math;

it would work.

like image 13
Chandermani Avatar answered Nov 10 '22 05:11

Chandermani


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'];
like image 1
fauverism Avatar answered Nov 10 '22 03:11

fauverism