【发布时间】:2013-06-25 13:07:52
【问题描述】:
angular-ui 的ui-select2 documentation 表明您可以执行以下操作:
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>
但是,在此之后对 $scope.select2Options 的更改没有任何作用。如果 ui-select2 会在这种情况下监视 select2Options 的更改并在它们发生更改时将它们发送到 select2,那就太好了。
我需要根据所选内容动态更改 maximumSelectionSize,并且执行以下操作显然是错误的,因为您不应该在控制器中弄乱 DOM。
<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>
内部控制器:
$scope.selectChange = function() {
if(...) {
$("#mySelect2").select2({ maximumSelectionSize: 1 });
} else {
$("#mySelect2").select2({ maximumSelectionSize: 0 });
}
}
如何在不使用 DOM 和在控制器中混合关注点的情况下将这些类型的选项传递给 select2? (我无法通过指令想出一个干净的方法来做到这一点。)
谢谢!
更新:
基于https://stackoverflow.com/a/16962249/405026、Stewie 的回答和我自己的测试,我已将以下代码添加到 angular-ui ui-select 的链接方法中:
try {
scope.uiSelect2 = angular.fromJson(attrs.uiSelect2);
} catch(e) {
scope.$watch(attrs.uiSelect2, function (opts) {
if (!opts) return;
elm.select2(opts);
}, true);
}
是否有更好的方法来处理 ui-select2 属性可能是对象字面量或作用域上的对象的情况?
【问题讨论】:
标签: angularjs jquery-select2 angular-ui