Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array is NaN? AngularJS ngModel

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?

What's going on here?

like image 261
Harry Avatar asked Feb 13 '23 19:02

Harry


2 Answers

$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

like image 142
Dave Alperovich Avatar answered Feb 15 '23 10:02

Dave Alperovich


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.

like image 35
Zach Snow Avatar answered Feb 15 '23 09:02

Zach Snow