When is $render() of ngModel called with real data?

I am writing a directive to cooperate with ngModel. As shown in the example, I set the $render function on the controller to my function.

When the code initializes, it is invoked twice, the first time with $modelValue and $viewValue set to NaN, and then a second time with the actual value of the model.

The problem is, NaN is a bear to test for. The function isNaN() is worthless, so far as I can see (it returns false for [""] but true for ["."] ) and Number.isNaN() is not widely supported.

Any suggestions?


我想出了一个关于如何测试NaN的问题的部分答案,但对我来说似乎仍然很尴尬。


The $modelValue and $viewValue of ngModel only ever assume (unless specifically assigned) the value of NaN in the very beginning - at link-time - and before any $formatters , $render and $validators (in that order) had a chance to run.

In other words, if you were to log at various points these values, you'd get the following (assuming the ngModel variable is set to "foo" ):

              link-time    $formatters     $render     $validators
              -----------------------------------------------------
$modelValue     NaN           "foo"         "foo"         "foo"
$viewValue      NaN            NaN          "foo"         "foo"

Demo

In words, unless you need to access ngModel at link -time, there is no need to guard against NaN . Moreover, there is also no double invocation - the ngModel pipe runs once per change.

Given the example you cite in comments my guess that you are seeing NaN in the $render function because you manually invoke the $render at link-time.

链接地址: http://www.djcxy.com/p/77928.html

上一篇: AngularJS:我如何在多个文件中创建控制器

下一篇: 什么时候用真实数据调用ngModel的$ render()?