Why is {{undefined + number}} returning a number?

I am working on an AngularJS project. I noticed that the following expression returns a number.

The view {{undefined + 10}} will display 10.

In JavaScript undefined + 10 NaN is output.

Why is this behavior different in presentation?

+47
javascript angularjs
Sep 06 '17 at 12:19 on
source share
2 answers

This is the advantage of interpolation.

AngularJS uses interpolation markup with inline expressions to bind data to text nodes and attribute values.

If the interpolated value is not a string, it is calculated as follows:

  • undefined and null convert to '' (empty string)
  • If the value is an object that is not a number, date, or an array, $interpolate looks up the custom toString() function for the object and uses it.
  • If the above does not apply, JSON.stringify used.

At runtime, the compiler uses the $interpolate service to see if text nodes and element attributes contain interpolation markup inline expressions.

In addition, the angular compiler uses interpolateDirective and registers observers to listen for model changes. This is a digest cycle process.

Read more here to understand how interpolation works.

Why does {{'' == +Infinity}} return true?

In angularJS, the $interpolate service evaluates +Infinity to 0 .

 angular.module('app', []) .controller('Controller', ['$injector', function($injector) { }]); setTimeout(function() { angular.bootstrap(document.getElementById('body'), ['app']); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <div id="body"> <div ng-controller="Controller"> {{+Infinity}} </div> </div> 

Now the expression remains {{0==''}} .

Why is 0=='' evaluated as true ?

The left side is of type Number . The right side is of type String .

In this case, the right operand is forced to the Number type:

 0 == Number('') => 0 == 0, 

which evaluates to true as a boolean value.

Here we use the Abstract Equality Comparison Algorithm .

If Type (x) is Number and Type (y) is String, return the result of the comparison x == ToNumber (y).

+47
Sep 06 '17 at 12:24
source share

To explain, referring to AngularJS code, this is magic:

 function plusFn(l, r) { if (typeof l === 'undefined') return r; if (typeof r === 'undefined') return l; return l + r; } 

If you have a plus expression, this function is analyzed in your template.

Replacing an expression is called Parser.parse (angular.js: 16155) or parse.js: 1646 ( https://github.com/angular/angular.js/blob/87a586eb9a23cfd0d0bb681cc778b4b8e5c8451d/src/ng/parse46.js# .

+9
06 Sep '17 at 14:01
source share



All Articles