简体   繁体   中英

How to define a variable from controller inside app.js in angularjs?

I want to open pages only when login is successful, I used flag in controller which I want to show in app.js as well.

headerCtrl.js:

$scope.verifyOTP = function(mobileNumber,otpNumber) {
   $rootScope.UserAuthorised=false;
   $http.get($scope.url,config).success(function(data, status) {
       $rootScope.UserAuthorised=true;
       $window.alert("Login Successfully!! ");
       var Mypath = '/home' ;
       $location.path(Mypath); 
       $location.replace();  
   })
}

App.js:

if($rootScope.UserAuthorised==true){
    adminApp.config(function($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl : 'pages/credentials/registration.html',
            controller  : ''
        })  
    })
} 

How do I define my variable in from controller into app.js so that i can change my flag from true to false and vice versa. Any help is appreciated. Thanks

headerCtrl.js

$scope.UserAuthorised=true; //remove this line and replace with following line
localStorage.setItem("UserAuthorised", "true");

App.js

$routeProvider.when('/secure', {templateUrl: '/secure.html', controller: 'Secure',resolve:{loggedIn:onlyLoggedIn}});

        var onlyLoggedIn = function ($location,$q) {
            var deferred = $q.defer();
            var isLogin = localStorage.getItem("UserAuthorised");
            if (isLogin == 'true') {
                deferred.resolve();
            } else {
                deferred.reject();
                $location.url('/login');
            }
            return deferred.promise;
        };

HeaderCtrl.js

$rootScope.UserAuthorised=true;

App.js

adminApp.config(function($routeProvider) {
$routeProvider
    .when('/home', {
        templateUrl : function($rootScope){
            if ($rootScope.UserAuthorised){
                  return  'pages/credentials/registration.html';
                  }
                  else return '/login.html';
        }
        controller  : ''
    })  
})

有很多方法可以执行此操作,如上所述,您可以使用$ window.sessionStorage,$ rootScope,并在可能的情况下使用Service处理控制器,然后再更改状态/位置。

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