【问题标题】:How to get Select2 tags initializing correctly with Angular UI when option groups are used?使用选项组时,如何使用 Angular UI 正确初始化 Select2 标记?
【发布时间】:2013-04-20 18:23:47
【问题描述】:

我一直在尝试让我的 angular ui select2 指令初始化,但无法让它与选项组一起使用。

守则:

function testCtrl1($scope)
{
    $scope.selectedOptions = ['1'];
    $scope.categories = [
            {label: 'cat1', options: [{desc: 'one', value: 1}]}, 
            {label: 'cat2', options: [{desc: 'two', value: 2}]}
    ];
}

HTML:

<select multiple ui-select2 ng-model="selectedOptions" style="width: 300px">
    <optgroup ng-repeat="category in categories" label="{{category.label}}">
      <option ng-repeat="option in category.options" value="{{option.value}}">{{option.desc}} - {{option.value}}</option>
    </optgroup>
</select>

小提琴: 我创建了以下jsfiddle

这样做时,我注意到如果我包含第二个不包含选项组的 select2 指令,它将正确初始化(奇怪)。在包含第二个 select2 时,我注意到其他一些奇怪的行为,但我不太关心它,因为我的目标只是让 testCtrl1 工作。

【问题讨论】:

标签: angularjs jquery-select2 angular-ui


【解决方案1】:

下载最新的 angular-ui select2 并更新第 24 行:

repeatOption = tElm.find( 'optgroup[ng-repeat], optgroup[data-ng-repeat], option[ng-repeat], option[data-ng-repeat]' );

现在它支持选项组。

【讨论】:

    【解决方案2】:

    好吧,我遇到了同样的障碍,想分享我的解决方案。 Select2 没有观察 optgroup ng-repeat 属性。您必须将其添加到您的 angular ui select2 指令中。

    改变这个:

    repeatOption = tElm.find('option[ng-repeat], option[data-ng-repeat]');
    

    至于:

    repeatOption = tElm.find('optgroup[ng-repeat], optgroup[data-ng-repeat], option[ng-repeat], option[data-ng-repeat]');
    

    不确定这是否是一个干净的解决方案,但它对我有用。

    Github issue

    【讨论】:

      【解决方案3】:

      select2支持&lt;optgroup&gt;通过分层数据,您可以将结构化对象作为数据传递而不是使用ng-repeat,参见
      http://ivaynberg.github.io/select2/#data_array
      同时在页面中搜索“Example Hierarchical Data”。

      JS:

      $scope.model = {
          data: [
              // both 'id' and 'text' are needed unless you write custom functions
              { text: 'cat1', children: [{id: 1, text: 'one'}] },
              { text: 'cat2', children: [{id: 2, text: 'two'}] }
          ]
      ];
      

      HTML:

      <input type="hidden" multiple ui-select2="model" 
          ng-model="selectedOptions" style="width: 300px">
      

      selectedOptions 将是一个对象数组:[ {id: 1, text: 'one'} ]

      有关通过指令的传递,请参阅 Angular UI 的演示:
      http://plnkr.co/edit/gist:4279651?p=preview

      编辑:更新代码和对站点的引用

      【讨论】:

      • 我刚刚尝试了这个选项:jsfiddle.net/tadchristiansen/X3pSb 并且输入也没有被初始化。选择的选项不在下拉列表中(正常工作),但它仍然没有显示在标签输入中。想法?
      • 我尝试将selectedOptions 设置为对象,但无济于事。想知道这是否是对象比较代码中的错误,我还将select2 更新为 3.3.2 但无济于事。 ui-select2 指令确实从我所看到的 (ivaynberg.github.io/select2/#programmatic) 中调用了 select2("data")。我认为下一步是调试器/日志记录。我的小提琴:jsfiddle.net/Jhfan/3
      猜你喜欢
      • 2023-03-09
      • 2015-01-21
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      相关资源
      最近更新 更多