How to listen on select2 events in AngularJS -


select2 provides custom events , want able listen them, particularly 'select2-removed' or better yet custom 'change' event, , i’ve been searching internet example, no luck.

here's i’ve done far:

html:

<input type="hidden" class="form-control" id="tags" ui-select2="modal.tags" data-placeholder="available tags" ng-model="form.tags"> 

javascript (angular)

$scope.form = {tags: []};  postaltags = [   {     id: 1,     text: 'permanent address'   },   {     id: 2,     text: 'present address'   } ];  $scope.modal {   tags: {     'data': postaltags,     'multiple': true   } };  // doubt going work, since think going  // listen on events emitted $emit , $broadcast. $scope.$on('select2-removed', function(event) {     console.log(event); });  // can this, not know removed , added $scope.$watch('form.tags', function(data) {   console.log(data); }); 

what user doing here edit tags tagged his/her address, , edit mean user can tag new tags his/her address or remove tagged tags. that's why need track tags added , removed.

update

i saw plausible solution on discussion, cant make provided code work mine, did workaround, , did.

so instead of adding the,

scope.$emit('select2:change', a); 

somewhere around here,

elm.select2(opts);  // set initial value - i'm not sure seems need there elm.val(controller.$viewvalue) 

i put here,

 if (!isselect) {         // set view , model value , update angular template manually ajax/multiple select2.         elm.bind("change", function (e) {            // custom added.           scope.$emit('select2:change', e);            e.stopimmediatepropagation(); 

then did usual on controller,

$scope.$on('select2:change', function(event, element) {   if(element.added) console.log(element.added);   if(element.removed) console.log(element.removed); } 

and works fine.

but doubt idea, , i'm still hoping better solution.

i used directive encapsulate select , in link function retrieve select element , @ event handler.

markup:

<select name="id" data-ng-model="tagsselection" ui-select2="select2options">     <option value="{{user.id}}" data-ng-repeat="user in users">{{user.name}}</option> </select> 

javascript:

link: function (scope, element, attributes) {     var select = element.find('select')[0];     $(select).on("change", function(evt) {         if (evt.added) {             //         } else if (evt.removed) {             // something.         }     });      $scope.select2options = {         multiple: true     } } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -