2

AngularJS で Select2 プラグインを使用すると問題が発生します。アイテムを正常にロードし、選択したアイテムを ng-model から取得できますが、ng-model を更新してもドロップダウンが更新されないという問題があります。

私の見解では、コードは次のようになります。

<select ui-select2 data-placeholder="All" id="filtersSelect" ng-model="chosenFilterItem" ng-options="item.text for item in filterItems">

私のコントローラーには、アイテムを取得してリストにバインドする次のコードがあります。

$scope.fetchFilters = function(){
        $http.get($scope.filtersUrl).then(function(result){
            $scope.filterItems = result.data;
            $scope.chosenFilterItem = result.data[3];
            if(!$scope.$$phase) {
                $scope.$apply();
            }
        });
    }

ご覧のとおり、ドロップダウンリストに 3 番目の項目を設定しようとしていますが、項目は事前に選択されていません。ドロップダウン項目を事前選択する別の方法はありますか?

4

2 に答える 2

6

Angular-ui/ui-select2 github ページの状態:

ui-select2 は と互換性がありません<select ng-options>。最良の結果を得るには、<option ng-repeat>代わりに使用してください。

したがって、頭痛から身を守るために、次のように 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>

デモプランカー

于 2013-06-21T11:59:37.670 に答える
1

Stewie は Select2 を実装する正しい方法を投稿しましたが、彼は「静的」要素を使用しています。

違いは、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>

うまくいかない場合は、ajax アイテムをロードする jsfiddle を作成してください。そこで作業します!

于 2013-06-22T10:21:25.503 に答える