Search code examples
angularjsauthenticationscopecontrollers

scope of controllers angularjs


My index.html looks like this:

<body ng-controller="ExternalCtrl">
  <div ng-include=" 'header.html' "></div>
  <div ng-view></div>
  <div ng-include=" 'footer.html' "></div>
<!-- all scripts, angular modules, directives, services etc.. -->
</body>

External controller wrap entire webpage, so I should have access to ExternalCtrl variables wherever in my app for example in headerCtrl which is controller of included header.html file.

I need this because in externalCtrl I get the value from localStorage (which are stored there after success login user) and if its present set a _authentication.isAuth = true; so I can develop my page with ng-if="_authentication.isAuth" for logged in users and ng-if="!_authentication.isAuth" for not logged in.

My externalCtrl code is:

'use strict';
app.controller('ExternalCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {

    var _authentication = {};

    var _authentication = {
        isAuth: false
    };

    var authData = localStorageService.get('authorization');
    if(authData) {

            _authentication.isAuth = true;
            console.log(_authentication.isAuth);

    }

}
]);

At this point console.log works correctly and log true if it is true or false if its false obviously.

After that I want to check if I have access to that variable in headerCtrl which is controller of included header.html as I mentioned above. So in this controller i add line:

console.log(_authentication.isAuth);

Which cause following error:

ReferenceError: _authentication is not defined

  1. Why?
  2. Is it correct way of doing this?

Solution

  • It is because _authentication is defined inside the controller. It is not available globally. You can define it on $scope or $rootScope.

     function($scope,$rootScope, localStorageService) {
    
           $scope._authentication = {};
    
            $scope._authentication = {
                isAuth: false
            };
    
            var authData = localStorageService.get('authorization');
            if(authData) {
    
                    $scope._authentication.isAuth = true;
                    console.log($scope._authentication.isAuth);
    
            }
    
        }
        ]);
    

    For more info: AngularJS access parent scope from child controller