AngularJS - UI Router stateChangeSuccess event not firing - angularjs

I am using UI Router in my angular app. I am trying to integrate state change events, but they are not firing on state change. Everything else is working fine and there is no error in console. I came across following similar questions, but none of the solution worked for me:
$rootScope.$on("$routeChangeSuccess) or $rootScope.$on("$stateChangeSuccess) does not work when using ui-router(AngularJS)
angular + ui-router: $stateChangeSuccess triggered on state b but not on a.b
Following is my Angular code:
(function() {
angular.module("bootdemo", [
"ngResource",
"ui.router",
"bootdemo.core",
"bootdemo.index"
])
.run(function ($rootScope, $location, $state, $stateParams) {
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
alert("root change success");
})
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
alert("root change start");
})
$rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){
alert("root change error");
})
})
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index', {
url: "/",
templateUrl: '/index/templates/welcome.html',
controller: 'IndexController as vm'
})
.state('login', {
url: "/login",
templateUrl: '/index/templates/login.html',
controller: 'LoginController as ctrl'
})
.state('home', {
url: "/home",
templateUrl: '/index/templates/home.html',
controller: 'HomeController as ctrl'
})
});
}());
Left with no clue. I am not sure what I am missing.

StateChange events has been deprecated for ui.router >= 1.0
for the new ui.router use the following
StateChangeSuccess
$transitions.onSuccess({}, function() {
console.log("statechange success");
});
StateChangeStart
$transitions.onStart({}, function(trans) {
console.log("statechange start");
});
Check this migration guide for more information

If you are using the new ui-router (v1.0.0), the $stateChange* events will not work. You must use $transitions.on* hooks from now on.
You can read here.
https://ui-router.github.io/docs/latest/modules/ng1_state_events.html
https://github.com/angular-ui/ui-router/issues/2720

$state events are deprecated for angular version > 1.0.0.
now onward for change event we have to use $transitions
refer $transitions from here

Related

angularjs-uirouter $state.go Error as .go undefined

Here imgetting Error in $statechangStart Here im trying to checking my credentials in $statechageStart
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('Login',{
url:'/LoginService',
templateUrl: '/ApiClient/Home/LoginPage.html',
controller:'LoginController'
})
$urlRouterProvider.otherwise('/')
})
.run(function ($rootScope) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope, $state) {
debugger;
if (toState.module == "Private" && sessionStorage.getItem('employee')!=null) {}
else {
event.preventDefault();
$state.go('Login');
}
You need to inject $state to your .run , otherwise it is undefined
.run(function ($rootScope, $state)
EDIT
It's a bad practice to use $state.go in $stateChangeStart event. For your purposes, you'd better apply the state.go after setting a timeout
$timeout($state.go.bind(null, 'Login'), 3000);

Angularjs ui-router 404 not evaluating

The scenario is rather simple I have a local site that uses angular. I have my state provider set up us ui router lib.
If I type in http://localhost.com/#/lwejfpwef it will redirect me properly to my other wise clause to the state '/login'.
However I tried typing in http://localhost.com/lwjpoifwef it doesn't fire off any of the events that I have in my module config.
I have tried
$stateChangeSuccess
$stateChangeStart
$stateChangeError
$httpinterceptors
I'm not sure what I am doing wrong. It doesn't seem to hit any of the break points I put in there. Here is a snippet of what I have
angular.module('app').run(['$rootScope', '$state', 'service', function ($rootScope, $state, service) {
$rootScope.$on('$stateChangeSuccess', function (evt, to, params) {
alert('success');
});
$rootScope.$on('$stateChangeStart', function (event, to, params) {
alert('start');
});
$rootScope.$on('$stateChangeError', function (evt, toState, toParams, fromState, fromParams, error) {
$state.go('login');
});
}]);
angular.module('dealer-portal.core').config(CoreConfig);
function CoreConfig($stateProvider, $urlRouterProvider, $httpProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'wwwroot/app/login/login.html',
data: {
displayName: 'Login'
}
})
.state('home', {
url: '/home',
templateUrl: 'wwwroot/app/login/login.html',
data: {
displayName: 'Home'
}
})
.state('error', {
url: '/login'
});
$urlRouterProvider.otherwise('/login');
}
$state.go should have the state name and not the url passed in
$state.go('login');
and NOT
$state.go('/login');
Also, you need to inject $stateParams in your run function

How to redirect to root if param is not found? Angular ui-router

I have the following routes, using Angular ui-router.
If I navigate to /3872 that gives me a user with that ID and the correct template, that's great.
But the problem is, if I type an ID that doesn't exist, such as /1111 I want to redirect to the root. At the moment it stays on the user route and gives me an empty template instead.
$stateProvider
.state('root', {
url: '/',
templateUrl: 'home.html',
controller: 'home_controller'
})
.state('user', {
url: '/:userId',
templateUrl: 'user.html',
controller: 'user_controller'
});
$urlRouterProvider.otherwise('/');
One way is to use $stateChangeStart event to make some filtering. That goes into app.run(...) section
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (toState.name == "user") {
//some logic... and most probably
//event.preventDefault();
//$state.go(toState.name, toParams);
}
});
In user_controller($stateParams,$state):
if($stateParams.userId not in userIds) {
$state.go('root');
}

ui-router change, when to remove the old html

I've tested this in chrome, and added a break in the $scope.init in Ctrl2
but then when I go to route2 from route1, the chrome debugger stays at $scope.init of Ctrl2, but I see that ctrl1.html is still there.
.state("main.route1", {
url: "/route1",
controller: 'Ctrl1',
templateUrl: 'views/ctrl1.html'
})
.state("main.route2", {
url: "/route2",
controller: 'Ctrl2',
templateUrl: 'views/ctrl2.html'
})
So, how does the ui-router work? Isn't it supposed to go to ctrl2.html, and then execute Ctrl2? Why did it enter Ctrl2 but the ctrl1.html is still displayed?
I'm not sure if it is the same in ng-view, I haven't tested that.
Check js console to make sure you don't have errors in your angular controller
Add following run block to your module to catch state change error
.run(function ($rootScope, $state) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
console.log(fromState.name + ' to ' + toState.name);
});
$rootScope.$on('$stateChangeError',
function (event, toState, toParams, fromState, fromParams, error) {
alert(error);
event.preventDefault();
});
});

Need to catch ui.router state and its url when the url changes

I wish to attach a listener to URL changes in the ui.router module I use in an AngularJS app, because I need to get the new state and its url when the url changes. In order to customize the url change listener, I've done the following, but it's not working (yet):
in the config section of ui.router, I added this line:
$urlRouterProvider.deferIntercept();
and after the config(), I have the following code, hoping to cactch the ui.router's state and its url
config(
//ui.router's config ommitted....
).run(function($rootScope, $urlRouter) {
$rootScope.$on('$locationChangeSuccess', function(e) {
console.log(e);
e.preventDefault(); //prevent the default handler
$urlRouter.sync(); //once the interception is done, sync the current url
$urlRouter.listen();
})
});
I am not sure if this is possible to do with ui.router. Or there is a much easier way to get the state and its url?
I am not 100% sure what is the real requirement behind. But with UI-Router, we should use $stateChangeStart event I'd say.
There is an example, a working plunker
$rootScope.$on('$stateChangeStart', function (event, toState, toParams
, fromState, fromParams)
{
console.log(event)
console.log(toState)
console.log(toParams)
console.log(fromState)
console.log(fromParams)
console.log(toState)
console.log($location.url())
});
Check it here
The $urlRouter and its .deferIntercept() and .listen() or more useful for declaring states in a .run() phase
// config
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProviderRef = $stateProvider;
$urlRouterProvider.otherwise('/home');
$urlRouterProvider.deferIntercept();
// run
.run(['$rootScope', '$urlRouter',
function($rootScope, $urlRouter) {
$stateProviderRef
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
})
$urlRouter.listen();
}
]);

Resources