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.
vm.search = 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
http://localhost:8000/app/#/search?q=%5Bobject%20Object%5D
Then I have to enter the query again and the url changes to
http://localhost:8000/app/#/search?q=userinput
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?
UPDATE I have this in a separate run.js file
.run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
UPDATE 2
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 controllerAs
syntax. Would it be wiser to just have an autocompleteCtrl
for the hp/query page and have a queryService injected into each controller for searchTerms
? Pls give a bit more time to fork the codepen, will send you comment when done.