Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material : How to add multiple chips when comma separated string is added in the input?

I'm using this syntax to create chips -

<md-chips ng-model="someModel" md-separator-keys="seperatorKeys">
                            <md-chip-template >
                                <span>{{$chip}}</span>
                            </md-chip-template>
                        </md-chips>

and this is part of the controller code.

$scope.seperatorKeys = [$mdConstant.KEY_CODE.ENTER, $mdConstant.KEY_CODE.COMMA];

Now I want to create multiple chips if I paste comma seperated string in the input to add chips, let's say, For e.g. if I enter 1234,5678 as an input, it should create 1234 as first chip and 5678 as second chip.

How can I achieve this functionality?

like image 938
Vishwajeet Vatharkar Avatar asked Mar 16 '17 13:03

Vishwajeet Vatharkar


1 Answers

Apparently the solution is very simple - something like following ---

In the controller, write a method to be used on md-transform-chip, and manipulate the array containing chips in the scope, using the method.

Then, return null so that no new chip will be created.

 $scope.addMultipleChips = function (chip, model) {
        var seperatedString = angular.copy(chip);
        seperatedString = seperatedString.toString();
        var chipsArray = seperatedString.split();
        angular.forEach(chipsArray, function (chipToAdd) {
            $scope[model].push(chipToAdd);
        });
        return null;
    };

And declare it in the template like this -

<md-chips ng-model="someModel" md-separator-keys="seperatorKeys"
md-transform-chip="addMultipleChips($chip, 'someModel')">
                                <md-chip-template >
                                    <span>{{$chip}}</span>
                                </md-chip-template>
                            </md-chips>

Here's a JSFiddle for the same. http://jsfiddle.net/vishwajeetv/2f6qscrp/255/

like image 143
Vishwajeet Vatharkar Avatar answered Oct 20 '22 13:10

Vishwajeet Vatharkar