floor 1: {{Math.fl...">
  

  

  

  
  

  
  



  
  
  

Why doesn't Math.floor return anything when we write it in angular HTML?

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); }); 

Output:

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

I usually look for the right way to get 1233 .

I do not want to call a new method in the controller.

Why doesn't Math.floor return anything?

Thanks,

Fiddle Demo

+6
source share
4 answers

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

$scope.Math=Math;

it will work.

+11
source

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

Your current scope is such that myCntrl defined, so ng-bind="value" evaluates to $scope.value .

AngularJS has no way to distinguish between the global Math namespace and $scope.Math , so it treats it like any other expressed expression.

I would recommend using $scope.Math=Math; .

The correct way to do this is to use filter :

 angular.module('myApp',[]).filter('floor', function(){ return function(n){ return Math.floor(n); }; }); 
+18
source

Put it in the 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']; 
+1
source

Angular expression does not support the whole javascript method, for example Math.floor (), you can moderate the floor function in the $ scope and delegete Meth floor

0
source

Source: https://habr.com/ru/post/958781/


All Articles