1

So what i want is to pass a variable for maxlength property of an input

  <input my-dir="maxLenght" id="inputScannedCode"
         type="text" ng-model="ScannedCode" maxlength="20"
         class="form-control orange-shadow" 
         required placeholder=" Scan the code " />

So i want the length of the input to be set from a constant for consistency.

so i've created a custom directive so that it changes the maxlength value.

.directive('myDir', function () {
    return {
        restrict: 'A',
        scope: {
            myDir: '='
        },
        template: '<div>{{myindex}}</div>',
        link: function (scope, element, attrs) {
            //console.log(attrs);
            //attrs.maxlength = scope.myDir.toString();
            //attrs.placeholder = scope.myDir.toString();            
        }          
    };
})

Indeed this changes my maxlength value but it does after compile but when i inspect my element it still shows maxlengh="20".

Any ideas what i need to do?

2 Answers 2

1

Use interpolation:

  <input my-dir="maxLenght" id="inputScannedCode"
         type="text" ng-model="ScannedCode" 
         maxlength="{{maxLenght || '20'}}"
         class="form-control orange-shadow" 
         required placeholder=" Scan the code " />

The $compile service will create a watcher that updates the maxlength attribute each time the Angular expression changes.

Sign up to request clarification or add additional context in comments.

Comments

0
  1. You might need to compile it using scope.eval in the link function like this to retrieve your value as you're using it in the link function

    attrs.myDir = scope.$eval(attrs.myDir);`

  2. And you are never setting the maxLength property on the input: you can use ng-maxlength for this: (angular documentation) which is the main reason it isn't updating

    <input my-dir="maxLenght" ng-maxlength="maxLength" id="inputScannedCode" type="text" ng-model="ScannedCode"  class="form-control orange-shadow" required placeholder=" Scan the code " />
    
  3. In your example you also misspelled "maxLength" as "maxLenght"

1 Comment

the problem is from what i could tell that maxLength is set to (let's say) 5 after the HTML page is rendered so the atribute keeps his original value ( logic ... ). I don't want to use ng-maxlength becouse this only makes the form that is nesting the input to be invalid, but it does allow user to exceed the number of chars set.

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.