小编Set*_*oyd的帖子

设置Angular-UI Select2多指令的初始值

我有一个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'} ...
]
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用以下方法在控制器中设置最初选择的值:

$scope.filters.countries = [{id: 'US', text: 'United States'}];
Run Code Online (Sandbox Code Playgroud)

这确实正确地设置了模型,但这是在select2初始化发生之前发生的.当我逐步执行剩余的初始化代码时,输​​入会[Object]在最终消隐$scope.filters.countries和输入之前暂时显示,但它不会在输入中显示占位符文本.

为了解决这个问题,我使用以下方法重置模型的初始值:

$scope.$on('$viewContentLoaded', function() {
    setTimeout(function() {
        $scope.filters.countries = [{id: 'US', text: 'United States'}];
    }, 100);
});
Run Code Online (Sandbox Code Playgroud)

使用a似乎非常hackish setTimeout.有没有更好的方法让我失踪?

更新1

根据ProLoser的要求,这里有一个demo和github票.

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

GitHub问题:https …

angularjs jquery-select2 angular-ui

21
推荐指数
1
解决办法
2万
查看次数

标签 统计

angular-ui ×1

angularjs ×1

jquery-select2 ×1