I use the angularjs ui-router to establish the various states within an app. While I know I can go to the state from a link in the html (via ui-sref), is it possible to go to the state from within a controller?
The code snippets below are a simple angularjs app to help illustrate my point.
In the example below, I have two states:
- There is a state called
home
that is a simple form containing a text input field and a button that calls a search function in the controller. - There is a state called
search
that takes a query parameter called text. Its controller calls a service that performs a search based on the text. The results are displayed to the page.
First is the module's initiation.
var app = angular.module('example', [
'ui.router'
]);
Below is the configuration of the ui-routing states as explained earlier.
app.config(
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.
state('home', {
url: '/',
template: '<input ng-model="text" type="text" placeholder="Query Text">' +
'<button type="button" ng-click="search()">Search</button>',
controller: 'SearchFormController'
}).
state('search', {
url: '/search?text',
template: '<pre>{{results | json}}</pre>',
controller: 'SearchController'
});
});
The SearchFormController controls the form input of search. This controller just forwards the form input to the search
state. Is it possible to reference the search state as opposed to constructing a URL and calling $location.path?
app.controller('SearchFormController',
function($scope, $location) {
$scope.text = '';
$scope.search = function() {
// Can I use the 'search' state here instead of
// constructing a url and calling $location.path?
$location.path('/search?text='+ encodeURIComponent($scope.text));
};
});
The controller of the search, SearchController, would look something like below. It would take the stateParams (i.e., query parameters) to issue an $http call.
app.controller('SearchController',
function($scope, $stateParams, $http) {
$scope.results = [];
asUrl = function(resourceUrl, queryParams) {
// do stuff and return http url
};
$http.get(asUrl("/someServiceUrl/search", $stateParams))
.success(function(data, status) {
$scope.results = data;
})
.error(function(data, status) {
// display an error message
});
});
Again, in the SearchFormController, is it possible to reference the search state from the config by name? For example, in an html page I could have a link like this: <a ui-sref="search({text:Foo})">Search where text=Foo</a>
where the search
state is referenced by name and passes in the parameters. Can something similar be invoked from a controller (by name, passing in parameters)?