Angular UI-Bootstrap Typeahead选中匹配项的回调函数?

95

我正在使用Angular UI-Bootstrap中的typeahead,并希望将其用作选择多个选项的方式,因此当selectMatch方法启动时,我需要获取所选值,但我在控制器中找不到如何实现它的方法。

<div class='container-fluid' ng-controller="TypeaheadCtrl">
<pre>Model: {{selected| json}}</pre>
<input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue">

如果我观察所选的值,每当按键被按下时我都会得到变化...

scope.$watch('selected', function(newValue, oldValue) {... });

我知道当用户按下回车键或点击列表时,会调用selectMatch方法,但我不知道如何在那个方法上设置回调...

谢谢!

4个回答

255

现在有更好的方法来完成这个任务。 新增了一种新的回调方法

在控制器文件中添加以下内容:

 $scope.onSelect = function ($item, $model, $label) {
    $scope.$item = $item;
    $scope.$model = $model;
    $scope.$label = $label;
};
在视图中添加以下内容:
 <input type="text"
        ng-model="selected"
        typeahead="state for state in states | filter:$viewValue"
        typeahead-editable="false"
        typeahead-on-select="onSelect($item, $model, $label)"/>

查看typeahead规范获取更多信息(搜索onSelect)。

检查以下URL是否有所帮助:http://www.techguides.in/how-to-create-autocomplete-using-angularjs-ui/

http://www.techguides.in/how-to-customize-autocomplete-to-display-multiple-columns-using-angularjs-ui-2/


2
谢谢!运行得非常好。这应该在Typeahead标题下的参考页面上正式记录:http://angular-ui.github.io/bootstrap/ - ariestav
30
有人知道在回调函数typeahead-on-select='onSelect($item, $model, $label)'中的$item、$model和$label对象实际上是什么吗? - AardVark71
@Matt,我们能否在使用onSelect事件时通过$http实现PostBack呢? - Pratik Gaikwad
16
@AardVark71,$item、$model和$label这三个属性分别如下所示。如果您绑定具有多个属性的JSON对象数组,则将在$item中获得选定的项目和所有属性。$model是内置的Angular模型,用于存储选定的item.value,而$label将在选择后为您提供文本框中显示的值。因此,简而言之,很多时候$label将等于$model。希望这澄清了您的疑虑。 - Pratik Gaikwad
17
如果表达式是这样的:state.id as state.name for state in states,那么解释起来会更容易。在这种情况下,$itemstate$modelstate.id$labelstate.name - Aximili
显示剩余2条评论

10

编辑:现在这种方法不是最好的。最好使用像上面答案中解释的onSelect回调函数。

我找到了如何做我想做的事情。我发现有一个typeahead-editable属性,如果将其设置为false,则仅当从模型中选择一个值时才会更改所选值。因此,$watch很好地起到了检查何时选择新值的作用。

<input type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue" typeahead-editable="false">

link: function(scope, elm, attrs){
    scope.$watch('selected', function(newValue, oldValue) {
        if (newValue)
          console.log(oldValue+"->"+newValue);
     });
}

3

以下应为您的 HTML 代码

 <input id="title" type="text"  ng-model="title"  typeahead="data.enquiry_title for data in titleData | filter:$viewValue | limitTo:8" 
typeahead-on-select='onSelect($item, $model, $label)' />

只需在输入标签中添加typeahead-on-select,并加入回调函数。

以下内容应放在控制器中

$scope.onSelect = function ($item, $model, $label) {
            console.log($item);
            if($item.tid)
                $scope.activeTitleId = $item.tid
        };

在$item内,您将获得您在建议列表的主数组中传递的整个对象。

0

在验证之前尝试以下操作

 modelCtrl.$setValidity('editable', true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接