Search code examples
angularjsng-tags-input

ngTagsInput disabled input after max tag number


I have a question, maybe someone used ngTagsInput in yours applications.

Is there an option to disable the input after you insert a max tags amount?


Solution

  • ngTagsInput has an ngModel accepting the array of tags so you can use ngDisabled to disable the input.

    Problem is if your input is disabled you wouldn't be able to remove any already existing tags and further edit the input. I wouldn't advice doing it.

    However you have some alternatives...

    1. Validate the amount of tags you have

    The API docs state that max-tags attribute is used to validate the max amount of tags inside the input, when you exceed the limit, the validation state will turn to $invalid, you can then prevent form submission.

    maxTags - number - Sets maxTags validation error key if the number of tags added is greater than maxTags.

    For example:

    <tags-input ng-model="tags" max-tags="7">
      <auto-complete source="loadTags($query)"></auto-complete>
    </tags-input>
    
    1. Use the on-tag-added callback attribute to catch when the user exceeds the allowed tags number and just remove any new tag he enters without playing around with validation flags

    HTML:

    <tags-input ng-model="tags" 
        on-tag-added="onTagAdded($query, 7)"></tags-input>
    <p>Model: {{tags}}</p>
    

    Controller:

    $scope.onTagAdded = function(tag, limit) {
        if ($scope.tags.length == limit+1) {
            $scope.tags.pop();
        }
    }
    

    In the above examples, we limit tags amount to 7.