gpt4 book ai didi

angularjs - 在 angularJs 中编写搜索文本框的正确方法

转载 作者:行者123 更新时间:2023-12-04 16:39:25 29 4
gpt4 key购买 nike

在我的应用程序的几个部分中,一个非常常见的功能是一个搜索框,它接受一个字符串,然后根据该字符串过滤一个表。

我的目标是允许用户输入内容并在延迟几毫秒后自动更新结果的能力。即无需点击输入按钮。

当然,数据的排序将使用 AngularJs 过滤器完成。然而,在我们更新过滤器之前,我相信我们首先必须了解用户已完成输入,现在正在等待结果。

所以我制定了将附加到搜索输入框的指令。

<input type="text"  update-filter placeholder="Enter search term">


//and the directive goes like this
app.directive('updateFilter', [ '$timeout', function($timeout){
var delay;
return {
link: function(scope, element){
element.on('keypress', function(){
if(!delay) {
delay = $timeout(function() {
//perform the activity of updating the filter here
delay = undefined;
},50);
}
}
}
}
});

我的问题是,这是解决这个问题的正确方法还是有更好的解决方案?

最佳答案

你把这个复杂化了。在 angular 中可以更容易地完成。

<input type="text" ng-model="query" ng-model-options="{ debounce: 200 }"
ng-change="doSearch()">

使用 $scope.query访问 Controller 中的查询。定义 $scope.doSearch()进行搜索。 debounce 选项用于在用户完成输入后等待 200 毫秒。

关于angularjs - 在 angularJs 中编写搜索文本框的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26931997/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com