控制器范围 angularjs

scope of controllers angularjs

我的 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 " 表示未登录。

我的外部Ctrl代码是:

'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则记录true,如果明显是false则记录false。

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

console.log(_authentication.isAuth);

导致以下错误:

ReferenceError: _authentication is not defined

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

因为_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