title: How to listen on select2 events in AngularJS
body: <p><a href="https://stackoverflow.com/a/22563038/2475170">select2</a> provides some custom events and i want to be able to listen to them, particularly the 'select2-removed' or better yet its custom 'change' event, and I’ve been searching the internet for some example, but with no luck.</p>
  
  <p>here's what I’ve done so far:</p>
  
  <p>HTML: </p>
  
  <pre><code>&lt;input type="hidden" class="form-control" id="tags" ui-select2="modal.tags" data-placeholder="Available Tags" ng-model="form.tags"&gt;
  </code></pre>
  
  <p>JavaScript (Angular)</p>
  
  <pre><code>$scope.form = {tags: []};
  
  postalTags = [
    {
      id: 1,
      text: 'Permanent Address'
    },
    {
      id: 2,
      text: 'Present Address'
    }
  ];
  
  $scope.modal {
    tags: {
      'data': postalTags,
      'multiple': true
    }
  };
  
  // I doubt this is going to work, since i think this is only going to 
  // listen on events emitted by $emit and $broadcast.
  $scope.$on('select2-removed', function(event) {
      console.log(event);
  });
  
  // I can do this, but then i will not know which was removed and added
  $scope.$watch('form.tags', function(data) {
    console.log(data);
  });
  </code></pre>
  
  <p>What the user actually is doing here is edit the tags tagged to his/her address, and by edit I mean the user can tag new tags to his/her address or remove previously tagged tags. That's why I need to track which tags where added and which are removed.</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I saw a plausible solution on this <a href="https://stackoverflow.com/a/22563038/2475170">discussion</a>, but i cant make the provided code to work with mine, so i did some workaround, and this is what i did.</p>
  
  <p>so instead of adding the,</p>
  
  <pre><code>scope.$emit('select2:change', a);
  </code></pre>
  
  <p>somewhere around here, </p>
  
  <pre><code>elm.select2(opts);
  
  // Set initial value - I'm not sure about this but it seems to need to be there
  elm.val(controller.$viewValue)
  </code></pre>
  
  <p>I put it here,</p>
  
  <pre><code> if (!isSelect) {
          // Set the view and model value and update the angular template manually for the ajax/multiple select2.
          elm.bind("change", function (e) {
  
            // custom added.
            scope.$emit('select2:change', e);
  
            e.stopImmediatePropagation();
  </code></pre>
  
  <p>then i did the usual on my controller,</p>
  
  <pre><code>$scope.$on('select2:change', function(event, element) {
    if(element.added) console.log(element.added);
    if(element.removed) console.log(element.removed);
  }
  </code></pre>
  
  <p>and works just fine. </p>
  
  <p>But i doubt this is very good idea, and i'm still hoping for a better solution.</p>