8

I'm having an issue getting my select2 on-change event to fire using Angular js.

Here is my html:

<select ui-select2="{allowClear:true}" data-placeholder="Select a Department" ng-change="DoSomething()" class="input-max" ng-model="l.DepartmentID">
    <option value=""></option>
    <option ng-repeat="d in l.LineLookups.Departments" value="{{d.DepartmentID}}">{{d.Type}}</option> </select>

When the select dropdown changes, the change event doesn't fire. Here's my event handler in my controller:

$scope.DoSomething = function () {
        alert('here');
        ...
}

What's the best way to handle this? I've been told to set a watch on the model value. Will that work, or is there a better way?

AnthonySG
  • 159
  • 1
  • 1
  • 7
  • Select2 has issues with Angular apparently, check out this Google group thread for some workarounds: https://groups.google.com/forum/#!msg/angular/YLcqj43ebR0/6gmayyHGz5MJ – tymeJV Sep 23 '13 at 20:40

3 Answers3

9

Alternative by watching ng-model:

In view:

<select ui-select2="{allowClear:true}" data-placeholder="Select a Department" class="input-max" ng-model="l.DepartmentID">
<option value=""></option>
<option ng-repeat="d in l.LineLookups.Departments" value="{{d.DepartmentID}}">{{d.Type}}</option>
</select>

In controller:

$scope.$watch('l.DepartmentID', function (newVal, oldVal) {
    if (oldVal == newVal) return;
    alert('here');
}, true);
Al Johri
  • 1,729
  • 22
  • 23
0

You could add a jquery listener to the angular-ui library, which then just fires an angular event - something like this:

  // Set initial value - I'm not sure about this but it seems to need to be there
  elm.select2('data', controller.$modelValue);
  elm.on('change', function() {
      scope.$emit('select2:change', elm);
  });

And then register an angular event listener int the controller:

    $scope.$on('select2:change', function (event, element) {
        console.log('change fired by' + element.get(0).id);
    });
Simon Green
  • 1,131
  • 1
  • 10
  • 28
0

I used a directive to encapsulate the select and then in the link function I just retrieve the select element and at the event handler.

Markup

<select 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) {
            // Do something
        } else if (evt.removed) {
            // Do something.
        }
    });

    $scope.select2Options = {
        multiple: true
    }
}
tazmaniax
  • 406
  • 1
  • 6
  • 13