我的index.html是这样的:范围angularjs
<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这是包含的头控制器.html文件。
我需要这个,因为在externalCtrl中,我从localStorage获得值(在成功登录用户后存储在那里),如果它存在,则设置_authentication.isAuth = true;这样我就可以发展自己的页面NG-IF = “_ authentication.isAuth”为登录用户和NG-IF =不登录
我externalCtrl代码为 “_ authentication.isAuth!”:
'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正常工作,如果它是真的还是假的,如果明显错误日志真实。
之后,我要检查,如果我有权访问headerCtrl该变量作为包括了header.html的控制器如我在上面提到。因此,在这个控制器我添加一行:
console.log(_authentication.isAuth);
引起以下错误:
ReferenceError: _authentication is not defined
- 为什么?
- 是不是这样做的正确方法?
因此,在嵌套控制器我没有访问到外部控制器定义的变量?我以为我有。 – BT101
不,你只是用父控制器内部的变种。你必须定义在$范围或$ rootScope变量。如果你正在使用$范围,然后在子控制器查看已打印{{$ parent.val}} – Vivz