AngularJS – How do I change the State from Inside the Controller

All we need is an easy explanation of the problem, so here it is.

I am new to AngularJS and would like to know how I change the State from within the Controller.

For example, I typically change the state on a button click:

<input type="submit" class="btn btn-lg btn-primary btn-block" value="Log In" ui-sref="main.navigation"/>

So on Submit of the button, my page will change to the navigation page. This works fine, but what if I want to do some logic in my controller first, and then based off the results, I would want to change to a specific page. How do I do this from within the controller, versus from a button click.

Here is my modules.js in case you are curious:

angular.module('ecsMain', [
    'ui.router',
    'ui.bootstrap',
    'ngTable'
])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('main/login');

    $stateProvider
        .state('main', {
            abstract: true,
            url: '',
            templateUrl: 'view/main.html'
        })
        .state('main.login', {
            url: '',
            controller: ECSMainController,
            templateUrl: 'view/login.html'
        })
        .state('main.phoneCalls', {
            url: '',
            controller: AccordionDemoCtrl,
            templateUrl: 'view/phoneCalls.html'
        })
        .state('main.navigation', {
            url: '',
            controller: ModalDemoCtrl,
            templateUrl: 'view/navigation.html'
        })
        .state('main.myModalContent', {
            url: '',
            controller: ModalDemoCtrl,
            templateUrl: 'view/myModalContent.html'
        })
        .state('main.alertMessage', {
            url: '',
            controller: ModalDemoCtrl,
            templateUrl: 'view/alertMessage.html'
        })
}]);

Thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

inject $state service to your controller, then in your controller…

CONTROLLER

$scope.changeState = function () {
    $state.go('where.ever.you.want.to.go', {stateParamKey: exampleParam});
};

and add ng-click to your button

HTML

<button ng-click="changeState()">Change State</button>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply