Search code examples
angularjsangularjs-directiveattributesdirectivemaxlength

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


Solution

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