Two way databinding in Select2 for AngularJS doesn't work

☆樱花仙子☆ 提交于 2019-12-22 13:51:33

问题


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.

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?


回答1:


Angular-ui/ui-select2 github page states:

ui-select2 is incompatible with <select ng-options>. For the best results use <option ng-repeat> instead.

So, to save yourself from headache I also recommend using options with ng-repeat as in:

$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




回答2:


Stewie posted the rigth way to implement Select2, but he's using "static" elements.

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.

<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!



来源:https://stackoverflow.com/questions/17137533/two-way-databinding-in-select2-for-angularjs-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!