问题
I'm trying to see what the value of an ngModel is:
.directive('myDir', function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ngModel) {
if (!ngModel)
return
console.log(ngModel)
console.log(ngModel.$modelValue)
}
};
})
Even though my ngModel is an array it logs NaN?

回答1:
$viewValue and $modelValue default to Number.NaN
-- JavaScript Definition for Not - a - Number.
check Github and you find that
var NgModelController = ['$scope', '$exceptionHandler', '$attrs',
'$element', '$parse',
'$animate', '$timeout',
function($scope, $exceptionHandler, $attr, $element, $parse,
$animate, $timeout)
{
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
Why is this convienient? Because AngularJS tries to avoid having cases like null
and undefined
. View Values and Model Values are bound and defined by "scope". That's the point of the $scope service -- to manage the modelValue and viewValue.
Until an AngularJS service accesses them, they are defaulted to number.NaN
回答2:
Presumably when you log ngModel
initially, ngModel.$modelValue
really is NaN
. Then you log ngModel.$modelValue
and you see it. Then various watchers and so on run, changing ngModel.$modelValue
to the array in question. Then you open the console-logged object (which you logged by reference, and which will therefore reflect changes) and see the changed value.
You can reproduce this easily in your console:
var s = {
some: 1,
big: [ 1, 2, 3 ],
object: [ "that gets a little drop-down arrow next to it when you log" ]
}
console.log(s);
s.some = "Changed!";
Click the dropdown next to the initial log and note that s.some
shows "Changed!"
instead of 1
, whereas the text next to the initial log remains 1
, as in your case.
回答3:
I'm not familiar with the specifics of Angular.js, but based on your screenshot and code I can offer an educated guess.
On the top line of the screenshot, an Object has been logged. The "preview" of that object (the not-expanded part) shows $modelValue: NaN
. The same NaN
is logged when you do console.log(ngModel.$modelValue)
. So at the instant that you log it, the value is NaN
.
For your object preview, hover over the little blue "i" icon and it will tell you "Object state is captured upon first expansion". That means that the state of the object might change some time between when you log it and when you expand it.
What I gather from this is that your ngModel
is initialized in some sort of "blank" state. You log it in that blank state, and see NaN
. Then something else changes it, then you expand it to see the $modelValue
is an array.
来源:https://stackoverflow.com/questions/24087888/javascript-array-is-nan-angularjs-ngmodel