我正在按照 https://github.com/angular-ui/ui-select2 中指定的方式使用 select2
<div ng-controller="sampleController>
<select ui-select2 ng-model="select2" data-placeholder="Pick a number">
<option value=""></option>
<option ng-repeat="number in range" value="{{number.value}}">{{number.text}}</option>
</select>
</div>
但这对我不起作用。我看到下拉菜单,但没有可供选择的值。
如果我将其更改为具有如下静态列表,则它可以正常工作。
<div ng-controller="sampleController">
<select ui-select2 ng-model="select2" data-placeholder="Pick a number">
<option value="">value1</option>
<option value="">value2</option>
<option value="">value3</option>
</select>
</div>
我在这里缺少什么?
我的模型如下
function sampleController($scope){
$scope.select2="";
$scope.range=[{text:"name1", value:"id1"},
{text:"name2", value:"id2"},
{text:"name3", value:"id3"}];
$("#e1").select2();
}
最佳答案
我认为你必须像这样使用 $timeout :
function sampleController($scope, $timeout){
$scope.select2="";
$scope.range=[{text:"name1", value:"id1"},
{text:"name2", value:"id2"},
{text:"name3", value:"id3"}];
$timeout(function(){
$("#e1").select2();
}, 0);
}
为什么?因为 $timeout 会在执行该函数之前等待 $digest (在您的情况下为 ng-repeat)结束。
您之前的代码是这样做的:
- 渲染 HTML
- $("#e1").select2();
- 解释 ng-repeat
因此,您的 select2 函数会在您的 select 具有其选项元素之前执行。
查看 $timeout 文档:https://docs.angularjs.org/api/ng/service/ $超时
关于javascript - AngularJS select2 不显示任何值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24459437/