user7370387
user7370387

Reputation: 99

AngularJS Directive does error when input is empty

I'm using this directive to limit my input to 5 caracters for percentage

   monApp.directive('awLimitLength', function () {
  return {
    restrict: "A",
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {
      attrs.$set("ngTrim", "false");
      var limitLength = parseInt(attrs.awLimitLength, 10);// console.log(attrs);
      scope.$watch(attrs.ngModel, function(newValue) { 
        if(ngModel.$viewValue.length>limitLength){
          ngModel.$setViewValue( ngModel.$viewValue.substring(0, limitLength ) );
          ngModel.$render();
        }
      });
    }
  };
})

and using it like this :

<input name="name" type="text"  ng-model="nameVar" aw-limit-length="5"/>

BUt when the input is empty, firebug notice several errors like this :

  Error: ngModel.$viewValue is undefined


Error: ngModel.$viewValue is null

How could i avoid theses errors ? Thank you. I'd like the directive not to be started when an input is empty.

I've tried this : But it doesn't work :

  monApp.directive('awLimitLength', function () {
  return {
    restrict: "A",
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {
      attrs.$set("ngTrim", "false");
      var limitLength = parseInt(attrs.awLimitLength, 5);// console.log(attrs);
      if(attrs.ngModel!=null){
          scope.$watch(attrs.ngModel, function(newValue) { 
            if(ngModel.$viewValue.length>limitLength){
              ngModel.$setViewValue( ngModel.$viewValue.substring(0, limitLength ) );
              ngModel.$render();
            }

          });
       }
    }
  };
})

Upvotes: 0

Views: 68

Answers (2)

Ankur
Ankur

Reputation: 3199

You have used require: 'ngModel' in directive. so you can't use this directive without value in model variable.

Remove require: 'ngModel' & it will work.

Upvotes: 0

Aravinder
Aravinder

Reputation: 503

Check ngModel.$viewValue exist before taking its length

scope.$watch(attrs.ngModel, function(newValue) { 
   if(ngModel.$viewValue && ngModel.$viewValue.length>limitLength){
      ngModel.$setViewValue( ngModel.$viewValue.substring(0, limitLength ) );
      ngModel.$render();
    }
  });

Upvotes: 1

Related Questions