2017-08-08 274 views
1

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

  1. 爲什麼?
  2. 是不是這樣做的正確方法?

回答

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

+0

因此,在嵌套控制器我沒有訪問到外部控制器定義的變量?我以爲我有。 – BT101

+0

不,你只是用父控制器內部的變種。你必須定義在$範圍或$ rootScope變量。如果你正在使用$範圍,然後在子控制器查看已打印{{$ parent.val}} – Vivz