34

我有一个预先输入的输入。输入文本设置为在预先输入时选择的选项。但是,在我从预先输入的选项中选择一个选项后,我想清除此文本并在文本框中再次显示“占位符”值(因为我将所选值添加到selectMatch()方法中的另一个 div。

<input id="searchTextBoxId" type="text" 
    ng-model="asyncSelected" placeholder="Search  addresses..."
    typeahead="address for address in getLocation($viewValue) | filter:$viewValue"
    typeahead-loading="loadingLocations" class="form-control"
    typeahead-on-select="selectMatch(asyncSelected)" typeahead-min-length="3"
    typeahead-wait-ms="500">

我尝试使用其 Id 设置 Input 元素的文本值和占位符值,但这不起作用,例如:

// the input text was still the 
$('#searchTextBoxId').attr('placeholder', 'HELLO');

选定的结果

// the input text was still the selected result
$('#searchTextBoxId').val('');

如何设置或重置文本值?

4

5 回答 5

51

我也在寻找这个问题的答案,时间最长。我终于找到了一个适合我的解决方案。

我最终将 NgModel 设置为属性中的字符串typeahead-on-select


在您的typeahead-on-select属性中添加asyncSelected = '';您的选择功能,如下所示:

<input ...
    typeahead-on-select="selectMatch(asyncSelected); asyncSelected = '';" />

使您的最终预输入看起来像:

<input id="searchTextBoxId" type="text" 
    ng-model="asyncSelected" placeholder="Search  addresses..."
    typeahead="address for address in getLocation($viewValue) | filter:$viewValue"
    typeahead-loading="loadingLocations" class="form-control"
    typeahead-on-select="selectMatch(asyncSelected); asyncSelected = '';" 
    typeahead-min-length="3"
    typeahead-wait-ms="500">

Fiddle adding each selection to an array

于 2014-04-23T15:09:57.793 回答
10

实际上这个问题不是来自预先输入的。这是关于ng-model, scope and dot notation.

请参阅 Angular 中的范围继承

在您的情况下,您只需像xx.selected使用点符号一样更改模型名称,并在 typeahead-on-select 回调中将 xx.selected 设置为空。

于 2014-11-07T02:56:38.327 回答
2

要设置或重置该值,您不会访问根据您的代码 asyncSelected 的 ng-model 值吗?在控制器中:

$scope.asyncSelected = '';
于 2014-02-28T20:10:41.090 回答
0

如果您需要立即清除价值, @Asok 的答案很好,但对于我自己,也许还有其他根据问题标题来到这里的人,@hey 的答案可能会更好(如果简洁的话)。

我改变了预输入如下:

<input id="searchTextBoxId" type="text" 
    ng-model="myNewVar.asyncSelected" placeholder="Search  addresses..."
    typeahead="address for address in getLocation($viewValue) | filter:$viewValue"
    typeahead-loading="loadingLocations" class="form-control"
    typeahead-on-select="selectMatch(myNewVar.asyncSelected)" typeahead-min-length="3"
    typeahead-wait-ms="500">

然后,每当我需要清除控制器的输入时,我都可以调用

$scope.myNewVar.asyncSelected = '';
于 2015-07-06T13:01:14.737 回答
0

我已经按照jnthnjns 的回答建议将 ng-model 的值设置为空字符串,但是选择弹出窗口并没有消失,因为我(有意)使用typeahead-min-length="0"以便用户可以轻松看到选择。

直到我注意到按回车键进行选择实际上关闭了该框,并且只有单击该框才保留。挖掘我看到的 ui-typeahead 代码

// return focus to the input element if a match was selected via a mouse click event
// use timeout to avoid $rootScope:inprog error
if (scope.$eval(attrs.typeaheadFocusOnSelect) !== false) {
   $timeout(function() { element[0].focus(); }, 0, false);
}

一旦我设置typeahead-focus-on-select="false",框就会在选择(并清除模型)后立即消失。现在看起来很明显,但我以前见过这个选项,但把它读作自动选择焦点(或类似的东西)。将此作为答案,以防万一它对其他人有所帮助。

于 2020-03-17T23:07:25.630 回答