2017-01-05 41 views
0

我的身体由MainController控制。在身体中,我有另一个嵌套控制器。在我的index.html,我具有由嵌套控制器控制的div元件:修改子控制器内的父控制器的变量AngularJS 1.x

的index.html

<body ng-controller="MainController"> 
    <div ng-controller="LoginController" ng-hide="isLoggedIn"></div> 
    <div class="navbar" ng-hide="!isLoggedIn"> 
    <!-- A form which calls login() function inside LoginController --> 
    </div> 
</body> 

MainController:

angular.module('DemoApp') 
    .controller('MainController', ['$scope', function ($scope) { 
    $scope.isLoggedIn = false; 
}]); 

的LoginController

angular.module('DemoApp') 
    .controller('LoginController', ['$scope', '$location', function ($scope, $location) { 
    $scope.login = function() { 
     if($scope.loginCredentials.username === 'username' && $scope.loginCredentials.password === 'password') { 
      $scope.parent.isLoggedIn = true; /* here, how to modify this variable */ 
      $location.path('/home'); 
     } 
    }; 
}]); 

我想要做的就是从我的嵌套控制器中更改MainController的变量,即isLoggedIn。我用$scope.parent,但它显示unknow provider parent。如何实现这一目标?

+1

使用$ localStorage存储isLoggedIn。并在需要时从$ localStorage获取。直到您手动清除密钥之前,此数据才可用。 –

+0

@SharanDeSilva谢谢,我将在未来使用它。 –

回答

2

您需要使用$parent来获取父控制器作用域,然后才能访问各种方法和属性。

$scope.$parent.isLoggedIn = true; 
+0

谢谢!另外,如果我再次进入主页,我需要将该变量设置为false。怎么做? –