10

我注意到 Angular-UI 已经停止使用他们的 UI-Select2 指令,转而使用新的 UI-Select(具有多个主题 - select2、bootstrap、selectize)。

它看起来像这样:

<ui-select multiple ng-model="multipleDemo.colors" theme="select2" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select colors...">{{$item}}</ui-select-match>
    <ui-select-choices repeat="color in availableColors | filter:$select.search">
        {{color}}
    </ui-select-choices>
</ui-select>

<p>Selected: {{multipleDemo.colors}}</p>

最初,我的选择框应该是空的,但准备好接受键入的字符,即至少 4 个字符的字符串,然后进行 API 调用以检索要填充框的建议值列表。然后将选择一个值,并根据需要重复搜索。

首先我尝试$watchng-model在这种情况下是multipleDemo.colors(使用演示中的这个例子)。API 调用从未发生过,然后我意识到了原因。实际模型根本没有改变,因为它只在进行选择时才会改变(我的选择框是空的,所以什么都不能选择)。

我的结论是我应该(能够)$watch作为过滤器添加的内容,即filter: $select.search.

有谁知道我应该如何在我的控制器中使用那个?

这个:

$scope.$watch('$select.search', function(newVal){
    alert(newVal);
});

不起作用。

编辑:供任何人参考,请参阅这个简短的讨论:是否可以添加对自定义查询功能的支持,如 select2?

编辑2:

我通过$emit在指令中使用解决了这个问题,因此该值现在可以在我的控制器中使用。但是现在我想知道如何覆盖指令的这一部分,以便指令本身可以保持不变,这样它就不会在未来的更新中中断?

4

5 回答 5

16

使用元素refresh上的属性以作为参数调用范围内的函数:<ui-select-choices>$select.search

<ui-select-choices repeat="color in multipleDemo.availableColors | filter:$select.search"
                   refresh="refreshColors($select.search)"
                   refresh-delay="0">
    {{color}}
</ui-select-choices>

然后使用函数(refreshColors()在此代码段中)进行multipleDemo.availableColors相应更新。

您还可以使用该refresh-delay属性来指定函数的去抖动时间,这样它就不会被快速连续调用太多次。

我也像你推荐availableColors的那样穿上。multipleDemomultipleDemo.colors

参考:ui-select 指令 wiki部分下的示例:异步

于 2014-11-06T03:43:31.867 回答
11

似乎有一个on-select属性,请参见Github 示例

<ui-select ng-model="person.selected" on-select="someFunction($item, $model)" [...]>
  [...]
</ui-select>
于 2014-10-23T22:50:06.940 回答
1

请耐心等待,这是我对 SO 的第一个回答。

所以目前的最佳答案对我不起作用。只是想提供另一种选择。ui-select-choices 上的 refresh 属性不会触发我范围内的命名函数。

我按照他们文档中的信息访问自定义功能的 UI 选择。$select.search创建一个自定义指令,您可以在其中观看

myModule.directive('myUiSelect', function() {
  return {
    require: 'uiSelect',
    link: function(scope, element, attrs, $select) {
      scope.$watch('$select.search', function (search) {
        if (search) {
          ...
        }
      });
    }
  };
});

然后在您的<ui-select my-ui-select>标签上包含该指令。

于 2016-08-23T21:05:44.890 回答
1

使用 ngInit 获取值,

<div ui-select ng-init="mySelect = $select"></div>
<button ng-click="search(mySelect.search)">Search</button>

您也可以改为观看“mySelect”

$scope.$watch('mySelect.search', function(newVal){
    alert(newVal);
});
于 2015-11-26T08:17:56.220 回答
-1

我通过在指令中的正确位置创建一个事件然后它来解决$emitting它 - 最终我能够在我的控制器中监听事件并使用该值。

这样做的缺点是我已将其直接放在第 3 方的指令中,因此无法安全更新。我需要找到一种方法来覆盖指令。如果您有任何想法,请告诉我。

于 2014-10-03T20:35:52.637 回答