David Dury
David Dury

Reputation: 5717

AngularJS UI-Router event when changing route

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?

Upvotes: 9

Views: 9220

Answers (3)

Stef
Stef

Reputation: 2683

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);
});

Upvotes: 0

Petru
Petru

Reputation: 914

Or just use

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

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

Upvotes: 1

karaxuna
karaxuna

Reputation: 26940

Yes it's possible:

$rootScope.$on("$stateChangeStart",
    function (event, toState, toParams, fromState, fromParams) {

Upvotes: 16

Related Questions