How can I pass option changes to Angular-UI ui-select2?

烈酒焚心 提交于 2019-12-11 04:43:22

问题


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?


回答1:


ui-select2 directive does not provide an API to this out-of-the-box, so you'd have to customize the directive to suit your needs by adding a $watcher on the select2 attribute (inside the directive linking function):

scope.$watch(attrs.uiSelect2, function(opts) {
  elm.select2(opts);
}, true);


来源:https://stackoverflow.com/questions/17353189/how-can-i-pass-option-changes-to-angular-ui-ui-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!