使用 Elasticsearch 和 AngularJS 开发一个小型搜索应用程序。我在 ng-submit 按钮上的 search() 中使用 $state.go()
。 searchTerms
是我输入的 ng-model。
我有 2 个 Controller ,homeCtrl 和 searchCtrl。 homeCtrl 用于主页,它只是一个搜索框并提供自动完成功能。 searchCtrl 用于结果页面,具有相同的搜索框并提供结果区域。
当我有这样的 $state.go()
时:
$state.go('search', {q: searchTerms});
它解决了我遇到的一个问题
http://localhost:8000/app/search?q=searchTerms
而不是
http://localhost:8000/app/search?q=userTypedInput
那么现在网址功能正常,但搜索结果不显示...?
<小时/>当我有
$state.go('search', {q: 'searchTerms'});
显示搜索结果,但网址未按预期运行。
所以基本上我要问的是如何让我的网址按预期运行
http://localhost:8000/app/search?q=userTypedInput
并且仍然显示搜索结果?
更新 这些是我的 ui 路由器状态
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home/home.html', controller: 'homeCtrl'})
.state('search', {
url: '/search?q',
views: {
'' : { templateUrl: 'search/search.html', controller: 'searchCtrl' }
//add more views here when necessary
}
});
搜索Ctrl
我把这个放在顶部
'use strict';
angular.module("searchApp.search", ['ngAnimate'])
.controller('searchCtrl', ['$scope', '$sce', '$stateParams', '$state', 'searchService', function($scope, $sce, $stateParams, $state, searchService) {
$scope.searchTerms = $stateParams.searchTerms || null;
这是 search(),其中包含 $state.go()
$scope.search = function() {
resetResults();
var searchTerms = $scope.searchTerms;
if (searchTerms) {
$scope.results.searchTerms = searchTerms;
} else {
return;
}
getResults();//calls searchService which does the searching
$state.go('search', {q: searchTerms});
};
var getResults = function() {
$scope.isSearching = true;
searchService.search($scope.results.searchTerms,$scope.currentPage,...
我正在尝试将网址设置为
http://localhost:8000/app/search?q=userTypedInput
并显示结果。
最佳答案
在状态配置中,您使用参数名称 q
来传递搜索查询。这是您在 searchCtrl
中从 $stateParams
访问参数时也需要使用的名称。在上面显示的代码中,您的查询将始终为空,因为您访问的名为 searchQuery
的参数不存在。
关于javascript - AngularJS 与 UI Router 的奇怪查询行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36483614/