【问题标题】:AngularJS strange query behavior with UI RouterAngularJS与UI路由器的奇怪查询行为
【发布时间】:2016-04-08 06:21:24
【问题描述】:

拥有一个使用 Elasticsearch 和 AngularJS 的小型搜索应用程序。我在我的 ng-submit 按钮上的 search() 中使用了$state.go()searchTerms 是我输入的 ng-model。

我有 2 个控制器,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

所以现在 url 功能正常,但搜索结果不显示...?


当我有

$state.go('search', {q: 'searchTerms'});

搜索结果显示,但 url 无法正常工作。

所以基本上我要问的是我怎样才能让我的网址按需要运行,这是

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
    }
  });

searchCtrl

我在顶部有这个

    '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

并同时显示结果。

【问题讨论】:

  • 禁用html5mode 并检查,否则它会起作用,让我知道
  • @swapnesh 我将 html5mode 设置为 false 并且没有更改,结果仍然不显示
  • 您没有提供必要的信息来找出这里的问题。 ui-router 负责构建 url 并加载页面。无法从您发布的代码中知道为什么没有显示结果
  • @user3125823 控制台有什么错误吗?
  • @swapnesh 控制台没有错误

标签: javascript angularjs


【解决方案1】:

在您的状态配置中,您使用q 的参数名称来传递搜索查询。这是名称,您在从$stateParams 访问searchCtrl 中的参数时也需要使用此名称。在上面显示的代码中,您的查询将始终为空,因为您访问了名为 searchQuery 的参数,该参数不存在。

【讨论】:

  • 非常感谢,我会在这里更正并报告。
  • 似乎我在状态配置中用于传递搜索查询的参数也应该与输入中的 ng-model 相同?我现在理解正确吗?我使用 q 因为它是输入的名称。
  • 一直在做更多的阅读,似乎我只是将我的 ng-model 更改为“q”,并在 searchCtrl 中用 q 替换 searchTerms - 一切都应该按预期工作......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2014-10-23
  • 2017-09-01
  • 2016-09-25
相关资源
最近更新 更多