简体   繁体   中英

How to call a function from a route in AngularJS

I'm developing an AngularJS project and I was wondering if it's possible to create a route that just calls a function, and then redirects.

I want to use this for having a /logout route that calls the logout() function on the authentication and authorization service and then redirects to /login .

A stripped version of my route configuration:

.when('/login', {
    templateUrl: '/app/login/login.html',
    controller: 'login'
})
.when('/logout', {
    redirectTo: '/login'
})

But obviously this doesn't actually logout the user (and because the user is still authorized the user is again returned to the root by the authorization service).

What would be a good solution to this? (The simplest solution being directly calling it from the menu, but this feels like a dirty hack that uses global scope.)

I don't think it's possible. As an alternative could you simply attach ng-click with logout() invocation and then redirect back to /login screen?

Run the function with ngInit

<div ng-init="runMe()"></div>

call the function which is inside the controller

app.controller('myController', function($scope){
    $scope.initialize = function () {
        alert("Kingdom");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM