model.$modelValue 在指令中是 NaN [英] model.$modelValue is NaN in directive
问题描述
看这个jsfiddle:http://jsfiddle.net/8bENp/66/
See this jsfiddle: http://jsfiddle.net/8bENp/66/
如果您查看 JavaScript 控制台,您会看到如下内容:
If you look at the JavaScript console, you'll see something like this:
TypeError: Object NaN has no method 'replace'
at makeHtml (https://raw.github.com/coreyti/showdown/master/compressed/showdown.js:62:705)
at render (http://fiddle.jshell.net/_display/:50:42)
at link (http://fiddle.jshell.net/_display/:54:13)
at k (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:42:321)
at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:38:198)
at k (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:42:261)
at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:38:198)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:37:332
at https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:15:440
at Object.e.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js:85:416) <markdown ng-model="someCode" class="ng-pristine ng-valid"> angular.min.js:60
问题在于 model.$modelValue
是 NaN
,而它的类型甚至不应该是数字.然而,降价呈现.我可以添加一个 typeof model.$modelValue == 'string'
检查,但我宁愿处理根本原因.有什么想法吗?
The problem is that model.$modelValue
is NaN
when its type shouldn't even be a number. Nevertheless, the markdown renders. I could add a typeof model.$modelValue == 'string'
check, but I'd rather treat the underlying cause. Any idea?
推荐答案
您的指令中的问题是 angular 在表达式计算之前触发了一次 watch.所以第一次值是 undefined
.我不相信这是可以防止的,但这就是 AngularJS 的工作原理.
The problem in your directive is that angular triggers the watch once before the expression has been evaluated. So the very first time the value is undefined
. I don't believe that can be prevented, but is how AngularJS works.
我在您的渲染函数中添加了一个 val
参数以显示实际监视值(记录到控制台 - 请参阅底部的小提琴).ngModelController
初始化$modelValue
到 NaN,这就是为什么 NaN
被传递给函数而不是 undefined
.
I added a val
parameter to your render function to show the actual watched value (logged to the console--see the fiddle at the bottom). The ngModelController
initializes $modelValue
to NaN, that's why NaN
is passed to the function instead of undefined
.
但是由于 makeHtml
函数似乎需要一个字符串,所以一个简单的解决方法是如果该值是假的,则将一个空字符串传递给它(将其转换为字符串可能更好).
But since it seems as if the makeHtml
function expects a string, an easy fix is to pass it an empty string if the value is falsy (might be even better to convert it to a string).
var htmlText = converter.makeHtml(model.$modelValue || '');
这篇关于model.$modelValue 在指令中是 NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!