简体   繁体   English

Select2 for AngularJS中的双向数据绑定不起作用

[英]Two way databinding in Select2 for AngularJS doesn't work

I am having issues with using the Select2 plugin in AngularJS. 我在使用AngularJS中的Select2插件时遇到问题。 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. 我可以加载项目,并从我的ng模型中检索所选项目,但我有问题,如果我更新ng模型,下拉列表不会更新。

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. 如您所见,我只是尝试在下拉列表中设置第3项,但没有预先选择项目。 Is there another way around preselecting a dropdown item? 还有另一种预选下拉项目的方法吗?

Angular-ui/ui-select2 github page states: Angular-ui / ui-select2 github页面状态:

ui-select2 is incompatible with <select ng-options> . ui-select2与<select ng-options>不兼容。 For the best results use <option ng-repeat> instead. 为了获得最佳结果,请使用<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>

DEMO PLUNKER DEMO PLUNKER

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,我会在那里工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM