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

北城以北 提交于 2019-12-24 08:37:26

问题


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?


回答1:


I came up with a partial answer to my question, about how to test for NaN, but it still seems awkward to me.




回答2:


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.



来源:https://stackoverflow.com/questions/30313950/when-is-render-of-ngmodel-called-with-real-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!