model. $ modelValue是指令中的NaN

Dis*_*tum 20 javascript angularjs angularjs-directive

看到这个jsfiddle:http://jsfiddle.net/8bENp/66/

如果你看一下JavaScript控制台,你会看到如下内容:

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
Run Code Online (Sandbox Code Playgroud)

问题是,model.$modelValueNaN当它的类型甚至不应该是一个数字.然而,减价呈现.我可以加一张typeof model.$modelValue == 'string'支票,但我宁愿对待根本原因.任何的想法?

小智 28

我不知道$ modelValue被初始化为NaN并遇到了类似的问题.如果在初始化时确实需要$ modelValue,则解决方案可能是在为其分配新值之前进行观察:

.directive('contentEditor', function(){
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, $element, $attrs, ngModel){

            var unregister = $scope.$watch(function(){
                return ngModel.$modelValue;
            }, initialize);

            function initialize(value){
                ngModel.$setViewValue(value);
                unregister();
            }

            //...
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

$ watch返回注销功能,因此只要为$ modelValue分配了新值,就可以取消注册.


小智 16

我想你也可以将它包装在一个ngModel.$render函数中.

像这样:

.directive('classOnValue', function($timeout) {
           return {
               restrict: 'A',
               require: 'ngModel',
               link: function(scope, element, attrs, ngModel) {

                   ngModel.$render = function(){
                       //Do something with your model
                       var actualValue = ngModel.$modelValue;
                   }

               }}
       })
Run Code Online (Sandbox Code Playgroud)


Mar*_*tin 12

你的指令中的问题是角度在表达式被评估之前触发了一次.所以这是价值的第一次undefined.我不相信可以预防,但是AngularJS是如何工作的.

val在渲染函数中添加了一个参数来显示实际监视的值(登录到控制台 - 请参阅底部的小提琴).在ngModelController 初始化$modelValue为NaN,这就是为什么NaN传递给函数代替undefined.

但是因为看起来好像makeHtml函数需要一个字符串,所以如果值为falsy(将它转换为字符串可能更好),一个简单的解决办法是将它传递给空字符串.

var htmlText = converter.makeHtml(model.$modelValue || '');
Run Code Online (Sandbox Code Playgroud)

更新了小提琴.