21

我有一个 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);
});

使用setTimeout. 有没有更好的方法让我想念?

更新 1

根据 ProLoser 的要求,这里有一个演示和 github 票。

演示:http ://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview

GitHub问题:https ://github.com/angular-ui/angular-ui/issues/455

按照 ProLoser 的建议,我开始使用 select2 的 initSelection 函数:

initSelection : function (element, callback) {
  callback($(element).data('$ngModelController').$modelValue);
},

它可以解决问题,但仍然感觉像是一种解决方法。

4

2 回答 2

8

根据 ProLoser 的要求,这里有一个演示和 github 票。

演示:http ://plnkr.co/edit/DgpGyegQxVm7zH1dZIJZ?p=preview

GitHub问题:https ://github.com/angular-ui/angular-ui/issues/455

按照 ProLoser 的建议,我开始使用 select2 的 initSelection 函数:

initSelection : function (element, callback) {
  callback($(element).data('$ngModelController').$modelValue);
},

它可以解决问题,但仍然感觉像是一种解决方法。

于 2013-08-16T05:00:57.330 回答
-1

您是否尝试过将选项初始化为:

<option selected value="0">Name</option>
于 2015-03-19T05:22:53.730 回答