控制器范围angularjs

时间:2017-08-08 15:45:13

标签: angularjs authentication scope controllers

我的index.html如下所示:

<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>

外部控制器包装整个网页,所以我应该可以访问我的应用程序中的ExternalCtrl变量,例如headerCtrl,它是包含的header.html文件的控制器。

我需要这个,因为在externalCtrl中我从localStorage获取值(在成功登录用户后存储在那里),如果它的当前设置为 _authentication.isAuth = true; ,那么我可以开发我的页面 ng-if =“_ authentication.isAuth”用于登录用户, ng-if =“!_ authentication.isAuth”未登录。

我的externalCtrl代码是:

'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);

    }

}
]);

此时 console.log 正常工作,如果为真,则返回true,如果显然为假则为false。

之后我想检查我是否可以访问headerCtrl中的那个变量,它是我上面提到的包含header.html的控制器。所以在这个控制器中我添加了一行:

console.log(_authentication.isAuth);

导致以下错误:

  

ReferenceError:未定义_authentication

  1. 为什么?
  2. 这样做是否正确?

1 个答案:

答案 0 :(得分:0)

这是因为在控制器内部定义了_authentication。它不是全球可用的。您可以在$scope$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);

        }

    }
    ]);

了解详情AngularJS access parent scope from child controller

相关问题