设置 Angular-UI Select2 多重指令的初始值 [英] Setting initial values of Angular-UI Select2 multiple directive
问题描述
我有一个 select2 指令,用于多个选择的国家/地区,并使用自定义查询来获取数据:
I have a select2 directive for a multiple select of countries with a custom query to grab the data:
// 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'} ...
]
我正在尝试使用以下方法在控制器中设置初始选定的值:
I'm trying to set the initially selected values in my controller using:
$scope.filters.countries = [{id: 'US', text: 'United States'}];
这确实正确设置了模型,但是这是在 select2 初始化之前发生的.当我逐步执行剩余的初始化代码时,输入临时显示 [Object]
,然后最终清空 $scope.filters.countries
和输入,但它不显示占位符输入中的文本.
This does correctly set the model, however this is happening before the select2 initialization has occurred. As I step through the remaining initialization code the input temporarily displays [Object]
before finally blanking out $scope.filters.countries
and the input, but it does not display the placeholder text in the input.
为了解决这个问题,我使用以下方法来重置模型的初始值:
To get around this I'm using the following to reset the models' initial value:
$scope.$on('$viewContentLoaded', function() {
setTimeout(function() {
$scope.filters.countries = [{id: 'US', text: 'United States'}];
}, 100);
});
使用 setTimeout
似乎真的很黑.有没有更好的方法让我想念?
It seems really hackish to be using a setTimeout
. Is there a better way that I'm missing?
根据 ProLoser 的要求,这里提供演示和 github 票证.
As requested by ProLoser here is a demo and github ticket.
演示:http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview
GitHub 问题:https://github.com/angular-ui/angular-ui/issues/455
按照 ProLoser 的建议,我开始使用 select2 的 initSelection 函数:
Following ProLoser's advice I started using select2's initSelection function:
initSelection : function (element, callback) {
callback($(element).data('$ngModelController').$modelValue);
},
它确实有效,但仍然感觉像是一种解决方法.
It does the trick but still feels like a workaround.
推荐答案
根据 ProLoser 的要求,这里是一个演示和 github 票证.
As requested by ProLoser here is a demo and github ticket.
演示:http://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview
GitHub 问题:https://github.com/angular-ui/angular-ui/issues/455
按照 ProLoser 的建议,我开始使用 select2 的 initSelection 函数:
Following ProLoser's advice I started using select2's initSelection function:
initSelection : function (element, callback) {
callback($(element).data('$ngModelController').$modelValue);
},
它确实有效,但仍然感觉像是一种解决方法.
It does the trick but still feels like a workaround.
这篇关于设置 Angular-UI Select2 多重指令的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!