Shane Shane - 3 months ago 13
Javascript Question

ng-model not getting passed in has-error class

I have a

template
below inside my
directive


<input ng-model="acc" type="number" required />
<p class="input-details" ng-class="{'has-error': confirm(acc, 3, 17)}"></p>


I have a method like this in my directive
controller
function

$scope.confirm= function(value, min, max) {
if (!value) return false;
return ("" + value).length < min || ("" + value).length > max;
};


The value is always passed as
undefined
in my
confirm
method, but when i call the same method in
ng-change
of my input like below, its getting passed.

<input ng-model="acc" type="number" ng-change="confirm(acc,3,17)" required />


Why is the
ng-class
not getting the correct
ng-model
value?

Answer

(""+3).length = 1 || (""+17).length = 2 because of type conversion see codepen for example crank the number input up and see what (""+acc).length equals and how to fix https://codepen.io/anon/pen/vKQZoR

app.controller('classTesterCtrl', function($scope, $log){
  $scope.confirm= function(value, min, max) {
    if($scope.acc < 3 || $scope.acc  > 17){
      $scope.valid = false;
    } else {
      $scope.valid = true;
    }
  };
});


<div ng-app="modelTest">
  <div ng-controller="classTesterCtrl">
    <input ng-model="acc" type="number" ng-change="confirm()" required />
  <p class="input-details" ng-class="{'has-error': valid}"></p>
    {{(""+acc).length}}
    {{acc}}
    {{valid}}
  </div>
  </div>