1

I am gonna get the count of letters in the textbox and show it in div tag which is featured by element directive .

  <input type="text" ng-model="name">
  <div counter-directive max-length="100" ng-model="name"></div>

div tag has to show something like this : 12/100 (12 is what we typed in input and 100 is the value of max-length )

the problem is , I don't know how to get the value of max-length .

here i have the example on jsfiddle

2 Answers 2

4

Firsly, check your spelling. You've used lenght a couple times in your question.

You can get the max-length attribute from the attrs object passed into the link function.

link: function (scope, element, attrs) {
    var foo = attrs.maxLength;
}
Sign up to request clarification or add additional context in comments.

Comments

2

You just have to do this:

app.directive('counterDirective', function () {

return {

    restrict: 'A',
    require: 'ngModel',
    scope: { maxLength:'=', ngModel:'&' },
    link: function (scope, element, attrs) {

            console.log(scope.maxLength);

        scope.$watch(scope.ngModel, function (value) {

            if (value) {

                var newValue = value.length;
                console.log(value);
                element[0].innerText = newValue;
            }
        });

    }
}

});

I think you have to replace 'lenght' by 'length' :)

5 Comments

Thanks for answer . but why scope.$watch does not work anymore when ngModel get change ?
It works for me, here is a plunker which display the new value in your directive each time you change your ngModel. jsfiddle.net/09nw12kc/7
Sorry I didnt understood your question. I updated the plunker and now it works properly :) jsfiddle.net/09nw12kc/9
yes it works . but as u told me above , i need use scope:{ maxLength:'=' } and get the value of attribute like scope.maxLength . in your jsfiddle i can see just my first example as i gave u without scope:{ maxLength:'=' } and ....
Thank u so much :)

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.