AngularJS ui路由器$ state.go无效

时间:2016-04-25 18:28:12

标签: angularjs

我有一个使用AngularJS和Elasticsearch的小型搜索应用程序,我试图让UI路由器的$state.go()将我的查询参数包含在网址中,但无法让它工作。 ..不知道为什么?

在Chrome的地址栏中:http://localhost:8000/app/search?q=searchTerms

即使在执行搜索后仍然保持这种状态 - 它应该是:http://localhost:8000/app/search?q=userTypedInput

在我的路线(州)中我有

$stateProvider
      .state('search', {
        url: '/search',
        url: '/search?q',
        $stateParams: {q: 'searchTerms'},
        views: {
          '' : {templateUrl: 'search/search2.html',
                controller: 'SearchCtrl',
                contollerAs: 'search'}
          //add more views here when necessary
        }
      });

在我的控制器中我有

    'use strict';

angular.module('searchApp.search', [])
    .controller('SearchCtrl', ['$scope', '$sce', '$state', '$stateParams', 'searchService', function($scope, $sce, $state, $stateParams,  searchService) {
        //Initialize
        //$scope.searchTerms = $stateParams || '';
    $scope.searchTerms = '';
        $scope.noResults = false;
        $scope.isSearching = false;

        //pagination
        //$scope.currentPage = 0;
        //$scope.itemsPerPage = 10;

        //results
      $scope.results = {
        queryTime: null,
        documentCount: null,
        documents: []
      };

$scope.search = function() {
    var searchTerms;
    $state.go('search', {q: 'searchTerms'});
    getResults();
  };

  var getResults = function() {
    $scope.isSearching = true;

    searchService.search($scope.searchTerms).then(function(response) {
... more code

我做错了什么?结果显示,我根本无法使用$ state.go获取url中的查询参数,因为我有它?

1 个答案:

答案 0 :(得分:0)

angular.module("myApp", []).run(["$rootScope","$state","$stateParams", function($rootScope, $state, $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
}]);

$stateProvider.state('search', {
    url: '/search?q',
    //don't specify $stateParams here
    views: {
        '': {
            templateUrl: 'search/search2.html',
            controller: 'SearchCtrl',
            controllerAS: 'search'
        }
        //add more views here when necessary
    }
});