angular-ui's ui-select2 documentation shows that you can do something like the following:
myAppModule.controller('MyController', function($scope) {
$scope.select2Options = {
allowClear:true
};
});
<select ui-select2="select2Options" ng-model="select2">
<option value="one">First</option>
<option value="two">Second</option>
<option value="three">Third</option>
</select>
However, changes to $scope.select2Options after that point do nothing. It would be nice if ui-select2 would watch select2Options for changes in that case and send them to select2 when they change.
I need to dynamically change maximumSelectionSize depending on what's selected, and doing something like the following is obviously the wrong thing to do since you shouldn't be messing with the DOM in a controller.
<select id="mySelect2" ui-select2="{ allowClear: true}" ng-model="select2" ng-change="selectChange()">
<option value="one">First</option>
<option value="two">Second</option>
<option value="three">Third</option>
</select>
inside controller:
$scope.selectChange = function() {
if(...) {
$("#mySelect2").select2({ maximumSelectionSize: 1 });
} else {
$("#mySelect2").select2({ maximumSelectionSize: 0 });
}
}
How can I pass those types of options through to select2 without using the DOM and mixing concerns in my controller? (I couldn't come up with a clean way to do this via a directive.)
Thanks!
Update:
Based on https://stackoverflow.com/a/16962249/405026, Stewie's answer, and my own testing I've added the following code to angular-ui ui-select's link method:
try {
scope.uiSelect2 = angular.fromJson(attrs.uiSelect2);
} catch(e) {
scope.$watch(attrs.uiSelect2, function (opts) {
if (!opts) return;
elm.select2(opts);
}, true);
}
Is there a better way of handling the case where the ui-select2 attribute may be either an object literal or an object on the scope?