Search code examples
angularjsangular-ui-routerangularjs-routingangular-controller

Angular : pass parameter to controller from $routeProvider.when


I perform a routing upon a broadcast and I need to pass a parameter from $rootScope.$on to a controller through routing.

$rootScope.$on('unauthorized_access', function (event, args) {
    $location.path('/login:' + args.msg);
});

Now, this is working.

$routeProvider
.when('/', {
    templateUrl: 'mainApp/landingPage/login.html'
})
.when('/login::msg', {
    templateUrl: function(params) {
        if (params) {
            // The params can be printed in console from here...
            console.log(params);
        }
        return 'mainApp/landingPage/login.html';
    },
    controller: 'loginController'
})
.otherwise({
    redirectTo: '/'
});

Now, so far it seems okay. But I need to pass the params to loginController. I tried,

.when('/login::msg', {
    templateUrl: function(params) {
        if (params) {
            console.log(params);
        }
        return 'mainApp/landingPage/login.html';
    },
    controller: 'loginController',
    pageParams : params
})

but I think, I am doing it wrong. Please help me. Any helps is appreciated. Thank you.

EDIT : I will add a scenario. I need to pass a message-string to loginController from any screen when the 'token' becomes invalid after a fixed time and user is redirected to login screen. Now, when the user arrives for the first time, there is no message to be shown. Hence, this is how I pass the message to broadcast

$rootScope.$broadcast('unauthorized_access', param);

Solution

  • Use resolve:

    $routeProvider
        .when("/news", {
            templateUrl: "newsView.html",
            controller: "newsController",
            resolve: {
                message: function(messageService){
                    return messageService.getMessage();
            }
        }
    });
    

    Then in your controller, you can get the data like below:

    app.controller("newsController", function (message) {
        $scope.message = message;
    });
    

    More on this:

    http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx