user3125823 user3125823 - 1 year ago 78
AngularJS Question

AngularJS UI Router and search

I've built a small search app using AngularJS, UI Router and Elasticsearch. I have 2 templates that share 1 controller. Everything works correctly ... except for for when I try to implement query parameters.

The one template is a simple hp to enter search query or select from autocomplete (UI Bootstrap Typeahead). The other template is for search results and more searching (search box and area to display search results).

My states look like this:

.state('query', {//home
url: '/',
templateUrl: 'search/query.html',
controller: 'searchCtrl as vm'
.state('search', {//results
url: '/search?q',
templateUrl: 'search/search.html',
controller: 'searchCtrl as vm'

I'm using $state.go (in searchCtrl) from UI Router to transition between states. = function() {
$state.go('search', {q: vm.searchTerms});

What's happening is that after you enter your query/select autocomplete it goes to the 'search' state but I see this is in the url


Then I have to enter the query again and the url changes to


Finally I have to enter the query yet again for search to execute. Obviously I want all this to happen with ONE search submission. What am I doing wrong?

Any suggestions or ideas?

I have this in a separate run.js file

.run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;

I'm getting the same error whether I use my code or your code. It seems to be that when I go from 'state' to 'state', that searchTerms is being reset due to the way $scope works in Angular. I'm not sure how to resolve that yet because I'm not sure if the solution provided there will work with
syntax. Would it be wiser to just have an
for the hp/query page and have a queryService injected into each controller for
? Pls give a bit more time to fork the codepen, will send you comment when done.

Answer Source

Which version of Angular 1 are you using?

I have put together a very quick and crude codepen with what I think you are trying to achieve, let me know if this what you are after and if it helps at all.

  .state('search', {
    url: '/',
    controller: 'myController as vm',
    template: '<div class="row"><form ng-submit="vm.query()"><div class="col-sm-10"><input class="form-control" ng-model=""></div><div class="col-sm-2">   <button class="btn btn-sm btn-default" ng-click="vm.query()">Search</button></div></form></div>'
  .state('query', {
    url: '/query?q',
    controller: 'myController as vm',
    template: '<div class="row">Query: {{}}</div>'


Update new CodePen - Working Pen

For some reason the order of Angular and UI Router had been changed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download