LearnAngular
LearnAngular

Reputation: 71

Restrict the length with the help of directive

I wanted to add a custom directive as attribute which will not allow user to enter text in placeholder more than specified length

   <ui-select-match placeholder="Add one..." maxlength></ui-select-match>

The new directive can be like "maxlength" which will restrict the length of text

Upvotes: 0

Views: 3188

Answers (1)

Ashokreddy
Ashokreddy

Reputation: 352

<textarea my-maxlength="15" ng-model="result"></textarea>

app.directive('myMaxlength', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
      var maxlength = Number(attrs.myMaxlength);
      function fromUser(text) {
          if (text.length > maxlength) {
            var transformedInput = text.substring(0, maxlength);
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
            return transformedInput;
          } 
          return text;
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  }; 
});

Upvotes: 2

Related Questions