0

How can I access a variable in my controller that is on the same file as my .config? I'm trying to authenticate if the user is currently login before loading a view like this:

'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'ngStorage',
  'ui.router',
  'myApp.userView',
  'myApp.usuarios'
])

.controller("MainCtrl",['$scope','$localStorage',function($scope,$localStorage) {

  $scope.user =  {}

  $scope.save = function(u) {
    $localStorage.user = u;
  };

  $scope.load = function() {
    $scope.user = $localStorage.user;
    console.log($scope.user);
  };

  $scope.logoff= function() {
    $localStorage.$reset();
    $scope.load();
  };

  $scope.loginPage= function() {

    var path = "/login/";
    window.location.href = path;
  };

  $scope.load();


}])

.config(function($stateProvider, $urlRouterProvider) {


    $urlRouterProvider.otherwise('/home');
   // $urlRouterProvider.otherwise('/404');

    $stateProvider

    .state('userView', {
        url: '/users_config',
        templateUrl: 'resources/userView/userView.html',
            controller: 'userViewCtrl',
        resolve: {
           security: ['$q', function($q){
               if($scope.user == null){
                 $state.go("401");
               }
           }]
        }
    })

    .state('404', {
        url: '{path:.*}',
        templateUrl: 'resources/errorView/404.html'
    })

    .state('401', {
        url: '{path:.*}',
        templateUrl: 'resources/errorView/401.html'
    });

});

I want to access $scope.user in the userView state to decide wheneaver it should be loaded or not. Any pointer would be appreciated.

beaver
  • 17,333
  • 2
  • 40
  • 66
Code Grasshopper
  • 610
  • 1
  • 11
  • 29

2 Answers2

2

You can't, $scope is create after the state is resolved.

Either use a service storing your current user or use $rootScope.

Walfrat
  • 5,363
  • 1
  • 16
  • 35
2

It is a good practice to implement login logic as a Service, like for example:

.factory("login_service", function ($http, $q) {
    var isLogged = false;

    function login(username, password) {
        var deferred = $q.defer();

        $http.post("/login", { username: username, password: password })
            .then(function (result) {
                if(result.data.error == 0) {
                    isLogged = true;
                    deferred.resolve(result.data);
                } else {
                    isLogged = false;
                    deferred.reject(error);
                }
            }, function (error) {
                isLogged = false;
                deferred.reject(error);
            });

        return deferred.promise;
    }
    function isLogged() {
        return isLogged;
    }
    return {
        login: login,
        logout: logout,
        isLogged: isLogged
    };
});

So you can inject login_service and use its methods (login, logout, isLogged) in all your controllers, in the resolve function of a state, in the .run() method of your Angular app.

You can implement eventually the login check in your .run() as follows:

app.run(function ($rootScope, $state, login_service) {

  $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
    event.preventDefault();
    if (login_service.isLogged()==false) {
        $state.go("login");
    } else {
        $state.go(toState.name, toParams);
    }
  });

});

Some usefull links:

Community
  • 1
  • 1
beaver
  • 17,333
  • 2
  • 40
  • 66