How to use $state.go() in UI-Router

Loading

In UI-Router (AngularJS), $state.go() is a method that allows you to programmatically navigate to a specific state. It is part of the UI-Router library and is an essential feature for handling state transitions without relying on URL changes or traditional browser navigation.

In this guide, we will explore how to use $state.go() to navigate between states and pass parameters in a UI-Router-based AngularJS application.


1. Setting Up UI-Router in an AngularJS Application

Before diving into $state.go(), let’s briefly set up UI-Router in your AngularJS application.

Install UI-Router

Add the UI-Router script to your index.html:

<script src="https://cdnjs.cloudflare.com/ajax/libs/ui-router/1.0.22/angular-ui-router.min.js"></script>

Include UI-Router in Your Application Module

Make sure to include the ui.router module in your AngularJS app’s dependencies:

var app = angular.module('myApp', ['ui.router']);

2. Defining States with $stateProvider

The $state.go() function works in conjunction with states defined via $stateProvider. Below is an example of how to define states in your AngularJS application:

app.config(function($stateProvider, $urlRouterProvider) {
// Default route
$urlRouterProvider.otherwise('/home');

// Define states
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
})
.state('user', {
url: '/user/:userId',
templateUrl: 'user.html',
controller: 'UserController'
});
});

In this example:

  • home and about are simple states.
  • user is a state that takes a dynamic parameter userId (indicated by :userId in the URL).

3. Using $state.go() to Navigate Programmatically

The $state.go() method is used to programmatically navigate to different states. It accepts the following arguments:

  • State Name: The name of the state you want to navigate to.
  • Parameters (Optional): Parameters that the state requires (if any).
  • Options (Optional): Additional options to control the transition behavior.

Basic Example of $state.go()

Here’s a simple example of how to use $state.go():

app.controller('HomeController', function($scope, $state) {
// Programmatically navigate to the 'about' state
$scope.goToAbout = function() {
$state.go('about');
};
});

In this example:

  • The controller for the home state defines a function goToAbout which, when called, uses $state.go('about') to navigate to the about state.

Example: Navigating to a State with Parameters

If a state requires parameters (like the user state in the example above), you can pass them using $state.go():

app.controller('HomeController', function($scope, $state) {
$scope.viewUserProfile = function(userId) {
// Navigate to the 'user' state and pass the userId parameter
$state.go('user', { userId: userId });
};
});

In this example:

  • The viewUserProfile function navigates to the user state and passes the userId parameter.

4. Additional Options for $state.go()

The $state.go() method also allows you to pass options that control how the state transition behaves. These options can be used to control behaviors like reload, inherit state parameters, and more.

Example with reload Option

By default, UI-Router doesn’t reload the controller and template if you’re navigating to the same state. If you want to force a reload, you can use the reload option:

$state.go('user', { userId: 123 }, { reload: true });

In this case:

  • The reload: true option ensures that even if the user state is already active, UI-Router will reload the state, including the controller and template.

Example with inherit Option

The inherit option ensures that parameters from the parent state are inherited in the child state:

$state.go('home.dashboard', {}, { inherit: true });

In this case:

  • The child state home.dashboard will inherit parameters from the home state.

5. Handling State Transitions Using $stateChangeStart

You can hook into state transitions using events such as $stateChangeStart, $stateChangeSuccess, and $stateChangeError. This can be useful for tasks like authentication checks, loading indicators, etc.

Example of Using $stateChangeStart

app.run(function($rootScope) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
console.log('Navigating from state:', fromState);
console.log('Navigating to state:', toState);
});
});

In this example:

  • The $stateChangeStart event listener logs the states being navigated from and to, along with their parameters.

6. Using $state.go() in the View

You can also trigger state transitions from the view using ui-sref directive, which is a declarative way to handle navigation in your HTML templates.

<button ui-sref="about">Go to About</button>

This is a shorthand for $state.go('about'), where the button, when clicked, will navigate to the about state.


7. Handling Return to Previous State

Sometimes, you might want to go back to the previous state. UI-Router provides a $state.previous property that you can use to get the last state:

app.controller('BackController', function($scope, $state) {
$scope.goBack = function() {
// Go back to the previous state
$state.go($state.previous);
};
});

This allows users to go back to the state they were previously on.


8. Full Example: Navigating Between States

Here’s an example combining all of the above concepts:

// Configure States
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');

$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
})
.state('user', {
url: '/user/:userId',
templateUrl: 'user.html',
controller: 'UserController'
});
});

// Home Controller
app.controller('HomeController', function($scope, $state) {
$scope.goToAbout = function() {
$state.go('about');
};

$scope.viewUserProfile = function(userId) {
$state.go('user', { userId: userId });
};
});

// About Controller
app.controller('AboutController', function($scope) {
$scope.message = 'This is the About Page';
});

// User Controller
app.controller('UserController', function($scope, $stateParams) {
$scope.userId = $stateParams.userId;
$scope.message = 'This is the profile for user ' + $scope.userId;
});

In the HTML templates, you would have buttons or links that trigger the $state.go() method:

<!-- Home Template -->
<button ng-click="goToAbout()">Go to About</button>
<button ng-click="viewUserProfile(123)">View User Profile</button>

Leave a Reply

Your email address will not be published. Required fields are marked *