AngularJS UI-Router event when changing route
Asked Answered
I

3

9

Using ngRoute once can hook up in event: $routeChangeStart and do different actions ...

 app.run(function ($rootScope, $location) {
    $rootScope.$on("$routeChangeStart", function (event, next, current) {
    ................

Is it possible to achieve the same using UI-Router?

Instigation answered 11/4, 2015 at 21:20 Comment(0)
D
16

Yes it's possible:

$rootScope.$on("$stateChangeStart",
    function (event, toState, toParams, fromState, fromParams) {
Distraction answered 11/4, 2015 at 21:47 Comment(3)
Will this be called every time a route changes? Or any time the app is run for the first time?Tearing
@Notflip every time before state changesDistraction
I ended up having to use $stateChangeSuccess because things weren't quite ready on $stateChangeStart, but thanks it got me where I needed to go.Lipoma
R
1

Or just use

$scope.$on("$stateChangeStart",...);

If you want this to be triggered on a single page.

Reviviscence answered 8/3, 2016 at 14:8 Comment(0)
R
0

Check this answer here, that's the correct way to fix it. Removing all listeners could have unknown effects as there might be other places where listeners are added. You need to remove the one you added, not all of them.

Check this issue: Angular $rootScope $on listeners in 'destroyed' controller keep running

Copying code here for completeness too:

animateApp.controller('mainController', function($scope, $rootScope, service) {
    $scope.pageClass = 'page-home';
    var unregister = $rootScope.$on('service.abc', function (newval) {
        console.log($scope.$id);
    });
    $scope.$on('$destroy', unregister);
});
Rotorua answered 21/6, 2019 at 2:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.