Forwarded state in corner

This is the state configuration:

angular .module('grabhutApp', [...]) .config(function ($stateProvider, $urlRouterProvider) { $stateProvider // ACCOUNT .state('account', { abstract: true, url: '/account', templateUrl: 'index.html' }) .state('account.main', { url: '', templateUrl: 'views/account/account.login.html', controller: 'AccountController' }) . . . // NO VIEWS .state('nv', { abstract: true, url: '/nv' }) .state('nv.logout', { url: '/logout' }) }); 

nv and its sub-states will not have any physical representations or controllers.
I want them to serve as links that invoke certain functions.

Service to call logout methods:

 angular.module('grabhutApp') .factory('$grabhutAccountService', function ($state, $grabhutDataService) { var methods = { . . logoutUser: function () { $grabhutDataService.user.removeSession(); $state.go('account.main', {}, {location: 'replace'}); } . . }; return methods; }); 

Then a button / link to exit:

 <a ui-sref="nv.logout" class="button icon icon ion-log-out button-large" menu-close></a> 

What I want is that when starting the state nv.logout $grabhutAccountService.logoutUser() should be called and should be redirected to 'account.main'

Here is what I have done so far:
I tried using the solution in nv.logout

 .state('nv.logout', { url: '/logout', resolve: { logout: function ($grabhutAccountService) { $grabhutAccountService.logoutUser(); } } }) 

The service was called, but the state was not redirected. So I tried another way. I added a controller:

 .state('nv.logout', { url: '/logout', resolve: { logout: function ($grabhutAccountService) { $grabhutAccountService.logoutUser(); } }, controller: function ($scope, $state) { $scope.$on('$stateChangeSuccess', function () { $state.go('account.main'); }); } }) 

But $stateChangeSuccess does not start.
So I tried using rootScope:

 .run(function(...., $grabhutAccountService){ . . . $rootScope.logout = function(){ $grabhutAccountService.logoutUser(); }; . . . }) 

And use it like this:

<a ng-click="$root.logout()" class="button icon icon ion-log-out button-large" menu-close></a>

It works great. But I'm worried, since (AFAIK) rootScope loads more data, which can cause slower operation.
Also, whenever I need a function like the one above, I will have to add the function to rootScope again.
And I think this is not a very good approach. By the way, I create this on the phone, so memory usage is so important.

+8
angularjs state angular-ui-router rootscope ionic-framework
source share
1 answer

Ohhh, you're so close. I rebuilt part of your code and came to this:

 app.run(function($rootScope, $grabhutAccountService) { $rootScope.$on('$stateChangeSuccess', function (evt, toState) { if (toState.name === 'nv.logout') { $grabhutAccountService.logoutUser(); $state.go('account.main'); } }); }); 

The next major version of the UI-Router will have significantly improved hooks for this.

+10
source share

All Articles