Angular JS + Redirect无法正常工作

时间:2016-05-16 05:20:19

标签: javascript angularjs angularjs-scope ngroute

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数据。

1 个答案:

答案 0 :(得分:1)

您没有状态logout

的模板
  

Angular在触发控制器之前使用if(模板)检查

解决这个问题:

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: '/',
        });
});