javascript Select2 for AngularJS 中的两种数据绑定不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17137533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two way databinding in Select2 for AngularJS doesn't work
提问by Dofs
I am having issues with using the Select2 plugin in AngularJS. I can load the items fine, and retrieve the selected item from my ng-model, but I have issues, that the dropdown isn't updated if I update the ng-model.
我在 AngularJS 中使用 Select2 插件时遇到问题。我可以很好地加载项目,并从我的 ng-model 中检索所选项目,但我有问题,如果我更新 ng-model,下拉列表不会更新。
In my view the code looks like this:
在我看来,代码如下所示:
<select ui-select2 data-placeholder="All" id="filtersSelect" ng-model="chosenFilterItem" ng-options="item.text for item in filterItems">
In my controller I have the following code, which retrieves the items and binds it to the list:
在我的控制器中,我有以下代码,它检索项目并将其绑定到列表:
$scope.fetchFilters = function(){
$http.get($scope.filtersUrl).then(function(result){
$scope.filterItems = result.data;
$scope.chosenFilterItem = result.data[3];
if(!$scope.$$phase) {
$scope.$apply();
}
});
}
As you can see I just try to set the 3rd item on the dropdownlist, but no item is preselected. Is there another way around preselecting a dropdown item?
如您所见,我只是尝试设置下拉列表中的第三项,但未预选任何项目。有没有另一种预选下拉项的方法?
回答by Stewie
Angular-ui/ui-select2github page states:
Angular-ui/ui-select2github 页面说明:
ui-select2 is incompatible with
<select ng-options>
. For the best results use<option ng-repeat>
instead.
ui-select2 与
<select ng-options>
. 为了获得最佳结果,请<option ng-repeat>
改用。
So, to save yourself from headache I also recommend using options with ng-repeat as in:
因此,为了避免头痛,我还建议使用 ng-repeat 选项,如下所示:
$scope.filterItems = [
{id: 1, text: 'Item1'},
{id: 2, text: 'Item2'},
{id: 3, text: 'Item3'},
{id: 4, text: 'Item4'}
];
<select ui-select2 placeholder="All" ng-model="chosenItem">
<option value=""></option>
<option ng-repeat="item in filterItems" value="{{item.id}}">{{item.text}}</option>
</select>
回答by Akallabeth
Stewie posted the rigth way to implement Select2, but he's using "static" elements.
Stewie 发布了实现 Select2 的正确方法,但他使用的是“静态”元素。
The difference is that angular renders select2 before having the elements called via ajax, so in this case you need to add an ui-if statement in order to add the directive only after you have data.
不同之处在于 angular 在通过 ajax 调用元素之前呈现 select2,因此在这种情况下,您需要添加一个 ui-if 语句,以便仅在您拥有数据后添加指令。
<select ui-select2 placeholder="All" ng-model="chosenFilterItem" **ui-if="filterItems.length>0"**>
<option value=""></option>
<option ng-repeat="item in filterItems" value="{{item.id}}">{{item.text}}</option>
</select>
If it doesn't work please create a jsfiddle with ajax items loading and I'll work there!
如果它不起作用,请创建一个加载 ajax 项目的 jsfiddle,我会在那里工作!