I use angularjs ui-router to set various states in the application. Although I know that I can go to state by reference in html (via ui-sref ), is it possible to go to state from the controller?
The code snippets below are a simple angularjs application that will help illustrate my point.
In the example below, I have two states:
- There is a state called
home , which is a simple form containing a text input field and a button that calls the search function in the controller. - There is a state called
search that accepts a text query parameter. Its controller calls a service that performs a text-based search. Results are displayed on the page.
Initialization of the module begins.
var app = angular.module('example', [ 'ui.router' ]);
The following is the configuration of ui-routing states, as described 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 element controls the input of the search form. This controller simply redirects form input to the search state. Is it possible to refer to the state of a search , and not to create a URL and call $ location.path ?
app.controller('SearchFormController', function($scope, $location) { $scope.text = ''; $scope.search = function() {
The SearchController will look something like this. To provide a $ http call for StateParams (i.e. request parameters) will require
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 SearchFormController , is it possible to refer to the search state from a configuration by name? For example, on an html page, I might have this link: <a ui-sref="search({text:Foo})">Search where text=Foo</a> , where the search state refers to the name and passes parameters. Can something like this be called from the controller (by name, passing parameters)?