0

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();
            }

          });
       }
    }
  };
})

2 Answers 2

1

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();
    }
  });
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you but where do i write this please
if(ngModel.$viewValue && ngModel.$viewValue.length>limitLength){ replace your if condition in $watch with this line
Thank you :) If it is useful and working please mark it as correct answer
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.