我有一个 select2 指令,用于多个选择的国家/地区,并使用自定义查询来获取数据:
// Directive
<input ng-model="filters.countries" ui-select2="filters.countryOptions"
data-placeholder="Choose a country...">
// filters.countryOptions
{
multiple: true,
query: function() {
get_list_of_countries();
}
}
// Formatted data from remote source
[
{id: 'US', text: 'United States'},
{id: 'CA', text: 'Canada'} ...
]
我正在尝试使用以下方法在控制器中设置最初选择的值:
$scope.filters.countries = [{id: 'US', text: 'United States'}];
这确实正确设置了模型,但是这是在 select2 初始化发生之前发生的。当我单步执行剩余的初始化代码时,输入暂时显示[Object]
在最终消失之前$scope.filters.countries
和输入,但它不显示输入中的占位符文本。
为了解决这个问题,我使用以下方法来重置模型的初始值:
$scope.$on('$viewContentLoaded', function() {
setTimeout(function() {
$scope.filters.countries = [{id: 'US', text: 'United States'}];
}, 100);
});
使用a似乎真的很黑客setTimeout
。我缺少的还有更好的方法吗?
Update 1
根据 ProLoser 的要求,这里有一个演示和 github 票证。
Demo: http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview
GitHub 问题:https://github.com/angular-ui/angular-ui/issues/455 https://github.com/angular-ui/angular-ui/issues/455
按照 ProLoser 的建议,我开始使用 select2 的 initSelection 函数:
initSelection : function (element, callback) {
callback($(element).data('$ngModelController').$modelValue);
},
它确实有效,但仍然感觉像是一种解决方法。