Angular JS + 重定向无效

Angular JS + Redirect not working

var weatherApp = angular.module('weatherApp', ['ngRoute', 'ngStorage']);

weatherApp.config(function ($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: 'html/views/search.html',
            controller: 'searchCtrl',
        })
        .when('/forecast',{
            templateUrl: 'html/views/forecast.html',
            controller: 'forecastCtrl',
        })
        .when('/login',{
            templateUrl: 'html/views/login.html',
            controller: 'loginCtrl',
        })
        .when('/logout', {
            controller: 'logoutCtrl',
        })
        .otherwise({
            redirectTo: '/',
        });
});

注销控制器

weatherApp.controller('logoutCtrl', ["$scope", "$location", "$localStorage", function($scope, $location, $localStorage){
    $localStorage.removeItem("user_email");
    $localStorage.removeItem("user_password");
    console.log("coming in logout controller!!");
    $location.path("/login");
}]);

我已经编写了上面的代码来为我的站点定义路由。对于注销,我将控制器定义为 "logoutCtrl"。但是我的代码似乎不起作用。当我点击 SITE_URL/#/logout 时,它既不控制台记录也不删除 localStorage 数据。

您没有状态模板logout

Angular uses an if (template) check before firing the controller

解决这个问题:

var weatherApp = angular.module('weatherApp', ['ngRoute', 'ngStorage']);

weatherApp.config(function ($routeProvider){
    $routeProvider
        .when('/', {
            templateUrl: 'html/views/search.html',
            controller: 'searchCtrl',
        })
        .when('/forecast',{
            templateUrl: 'html/views/forecast.html',
            controller: 'forecastCtrl',
        })
        .when('/login',{
            templateUrl: 'html/views/login.html',
            controller: 'loginCtrl',
        })
        .when('/logout', {
            template: " ", // <--- Notice, (" ") rather than ("")
            controller: 'logoutCtrl',
        })
        .otherwise({
            redirectTo: '/',
        });
});