Hugo Forte
Hugo Forte

Reputation: 5978

AngularUI select2 onChange method

How do I go about doing something along these lines:

   <select ui-select2 multiple="true" on-change="onChange()" data-ng-model="select2Model"></select>

where in my controller, I have the onChange(select2OnChangeData) defined.

I tried adding this

    scope: {
        model: "=ngModel",
        onChange: "&onChange"
    },

to angular-ui, but that changed the scope variable and broke the rest of the functionality.

I'd really like to refrain from doing:

.on("change", function(e)

Upvotes: 1

Views: 8420

Answers (1)

Mike Robinson
Mike Robinson

Reputation: 25159

Good thing I did just this in my project:

HTML

<select data-placeholder="Select an asset" class="input-xxlarge" ui-select2="sourceAssetId" ng-model="sourceAssetId" ng-options="asset.id as asset.name for asset in assets"></select>

Directive

module.directive("uiSelect2", function() {
    var linker = function(scope, element, attr) {
        element.select2();

        scope.$watch(attr.ngModel, function(newValue, oldValue) {
            console.log("uiSelect", attr.ngModel, newValue, oldValue);

            // Give the new options time to render
            setTimeout(function() {
                if(newValue) element.trigger("change");
            })
        });
    }

    return {
        link: linker
    }
});

Relevant Controller Code

$scope.$watch("sourceAssetId", function(newValue, oldValue) {
    if(newValue) $scope.fetchAsset();
});

Upvotes: 2

Related Questions