如何在新搜索结果显示之前保持显示结果

时间:2017-01-10 00:07:20

标签: angularjs

由于查询结果较低,在我的AngularJS应用程序中,当我单击搜索按钮以请求新搜索时,我的页面将显示我的预定义错误消息"没有相关的搜索结果,如您所愿" ,一两秒后,我的查询完成,我的页面刷新以显示我的新搜索结果。

我想在新的搜索结果显示之前保留显示的结果? 有任何建议或暗示吗?感谢。

1 个答案:

答案 0 :(得分:0)

这取决于您放置代码以清除或替换结果列表的位置。

您好像在控制器中执行此类操作:

runSearch(searchText) {
     this.results = []; // this shows your "no results" text
     this.$http.get('/search?q=' + searchText).then(res => this.results = res.data);
}

相反,只需删除第一行,这样您只需在HTTP调用返回后替换结果:

runSearch(searchText) {
     this.$http.get('/search?q=' + searchText).then(res => this.results = res.data);
}

说明

runSearch内有两个点,Angular会为您更新页面:

  1. 运行该函数后,但在HTTP调用返回之前
  2. HTTP调用返回后
  3. 这里他们在代码中:

    runSearch(searchText) {
        // #1 - any code here will update the page immediately
        this.$http.get('/search?q=' + searchText)
            .then(function (res) {
                // #2 - any code here will update the page when the HTTP call returns
            });
        // (#1 - if you have any code here it will also update the page immediately)
    }
    

    技术原因是Angular会在runSearch()调用中调用您的$scope.$apply()函数,调用您的函数,然后运行所有范围的完整摘要应用程序。这就是Angular能够看到更改并更新页面的原因。但是,在初始摘要完成后,您在.then()承诺上传递给$http的函数会在稍后执行。但Angular将调用.then()内的另一个函数(传递给$scope.$apply()),这会触发另一个摘要,并允许Angular查看并应用对页面的任何更改。那个时候。

    如果您考虑要实现的目标,只需在返回搜索结果后更新页面(上述代码中的#2)。因此,只需将代码放在那里,就可以在正确的时间更新页面,而不是之前。