0

Is there an easy way for defining a placeholder text for each textbox

in the form of:

"Please enter a maximum of X Chars" where X is the content of ng-maxlength

Or do I have to write it that way manually:

<input class="form-control" ng-model="valueBag.test" 
    ng-maxlength="30"
    placeholder="Please enter a maximum of 30 Chars">

I have already a form with 30+ existing inputs and I want to add the placeholder to each of them (which would be great to do it not manually).

1 Answer 1

2

I think you could just create a simple directive:

app.directive('formControl', function() {
  return {
    restrict: 'C',
     link: function(scope, e, attr) {
         var el = e;
         if (attr['ngMaxlength']) {
             el.attr('placeholder', 'Please enter a maximum of ' + attr['ngMaxlength'] + ' Chars')
         }
     }
  }
});

This would be applied to any element that has class form-control and ng-maxlength set.

Demo: http://plnkr.co/edit/m1K49L2pHAHaAmfXrrk6?p=preview

You probably could get away with creating an input element directive so the class isn't required:

app.directive('input', function() {
  return {
    restrict: 'E',
     link: function(scope, e, attr) {
         var el = e;
         if (attr['ngMaxlength']) {
             el.attr('placeholder', 'Please enter a maximum of ' + attr['ngMaxlength'] + ' Chars')
         }
     }
  }
});

The angular help docs on directive are now great (not so in the past): http://docs.angularjs.org/guide/directive

2
  • no need for angular.element(e) and el.hasClass('form-control') Feb 7, 2014 at 13:11
  • You are right, I did that before my morning coffee!
    – lucuma
    Feb 7, 2014 at 13:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.