How to get the selected chip angular materials?

You can select the md-chip elements in md-chips by clicking on them, but I have not found a good method to find out which one is selected in the controller.

Has anyone done this?

 <md-chips ng-model="ctrl.roFruitNames"> <md-chip-template> <strong>{{$chip}}</strong> <em>(fruit)</em> </md-chip-template> </md-chips> 

http://codepen.io/anon/pen/QbOaLz

+6
source share
5 answers

Unfortunately, as far as I can see in the Angular Material code, this does not appear in the current md-chip implementation.

You can get around this by contacting the directory controller directly, but it is pretty dirty and will break easily with future versions of md-chip .

 <md-chips ng-model="ctrl.roFruitNames" ng-click="ctrl.getSelectedChip($event)"> 

In the controller:

 self.getSelectedChipIndex = function(event) { var selectedChip = angular.element(event.currentTarget).controller('mdChips').selectedChip; alert(selectedChip); } 

See how it works:

http://codepen.io/anon/pen/oXopQq

In Angular, the problem arises when something like this is requested, so hopefully it will be added in the future:

https://github.com/angular/material/issues/3413


[change]

to extract chip data:

  var ctrl = angular.element(event.currentTarget).controller('mdChips'); if(ctrl !== undefined){ var selectedChip = ctrl.items[ctrl.selectedChip]; } 
+6
source

Use md-on-select: An expression to be called when the chip is selected.

  <md-chips md-on-select="getChipInfo($chip)" md-on-remove="removeChip($chip)"> ... </md-chip> 

In your controller

 $scope.getChipInfo= function(chip_info) { console.log(chip_info); } 
+11
source

Have you tried md-chips' md-on-select ? In the Codepen you used, you use Angular Material v0.10, with which md-on-select does not work, but if you change it to v0.11.4, it works:

 <md-chips md-on-select="ctrl.select($chip)"> 

In the controller:

 self.select = function(chip) { // You got the chip! } 

Here's a forked version of your Codepen: http://codepen.io/anon/pen/vLmKQR

API MD Chips: https://material.angularjs.org/latest/api/directive/mdChips

Just note that if md-on-add does not work, use md-on-append instead, although it will be removed in the official release of version 1.0.

+1
source

You can call a function in your scope with ng-click :

 <md-chip-template ng-click="ctrl.doSomething($chip)" > 
0
source

It should be md-on-add

 <md-chips md-on-add="ctrl.select($chip)"> 

or

 <md-chips md-on-add="yourmodel=ctrl.chipModel"> 
0
source

Source: https://habr.com/ru/post/989672/


All Articles