Hanna Hanna - 3 months ago 64
AngularJS Question

How can I restrict characters of a md-chip value?

I am using md-chips. Now I want to limit the character as 10.

I tried md-maxlength, one custome directive to limit characters but its all working in textarea and input not in chips

Answer

Chip Limit


Limits the count of chips you can add to the 'chips' model:

<md-chips ng-model="myItems" placeholder="Add an item" md-max-chips="5">
</md-chips>

Demo: https://jsfiddle.net/suunyz3e/290/

You cannot add more than 5 chips to that input.

Unfortunately there's very little validation control for the md-chips directive:

From (AngularJS Material)

Validation

  • allow a validation callback
  • hilighting style for invalid chips

Character Chip Limit


If you're after a character limit, you can do something like this:

<md-chips ng-model="myItems" placeholder="Add an item" md-max-chips="5"  md-on-add="validateChip($chip)">
</md-chips>

Controller:

angular.module('sandbox', ['ngMaterial']).controller('testCtrl', function($scope) {
    $scope.myItems = [];
    $scope.validateChip = validateChip;

    var characterLimit = 10;
    function validateChip($chip) {
        if (!$chip) return;
        // check if the current string length is greater than or equal to a character limit.
        if ($chip.length >= characterLimit) {
            alert('whooaaa, you breached the limit yo!');
            // remove the last added item.
            $scope.myItems.pop();
        }
    }
});

Demo: https://jsfiddle.net/suunyz3e/291/