Search code examples
javascriptangularjsangularjs-scope

Modify variable of parent controller inside child controller AngularJS 1.x


I have my body controlled by a MainController. In the body, I have another nested controller. In my index.html, I have a div element controlled by the nested controller:

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

All I want to do is change the variables of MainController, which is isLoggedIn, from my nested controllers. I used $scope.parent, but it shows unknow provider parent. How to achieve this?


Solution

  • You need to use $parent to get the parent controller scope, then various methods and properties can be accessed.

    $scope.$parent.isLoggedIn = true;