Search code examples
angularjsangularjs-scopeangularjs-ng-include

Can't access $parent from ng-included controller


I'm pretty new to Angular and I'm trying to build an app.

I use ng-include to insert my view, depending on the currentURL variable of my main controller. When I try to access the main controller via $parent from the ng-included file, all I get is undefined.

My goal is to change the currentURL variable to update the view.

Here is my code:

index.html

<body ng-controller="mainCtrl as main">
    currentURL : {{main.currentURL}}
    <div ng-include="main.currentURL"></div>

    <script src="/vendors/angular.min.js"></script>
    <script src="/modules/login.js"></script>
    <script src="app.js"></script>
</body>

app.js

angular
    .module('mcaApp', ['login'])
    .controller('mainCtrl', mainCtrl);

function mainCtrl() {
    var vm = this,
        baseURL = 'views/';
    vm.currentURL = baseURL + 'login.html';
}

views/login.html

<div ng-controller="loginCtrl as login">
    <h1>LOGIN</h1>
</div>

modules/login.js

angular
    .module('login', [])
    .controller('loginCtrl', loginCtrl);

function loginCtrl() {
    var vm = this;

    console.log(vm.$parent); // undefined
}

Solution

  • As you want to access mainCtrl which was inside loginCtrl controller then you need use $parent to access parent controller scope.

    But the thing is you are loading loginCtrl controller view using ng-include so your controller is loaded in the child scope of the mainCtrl, because ng-include create a child scope from current scope.

    For that reason you need use $parent.$parent to access mainCtrl scope from loginCtrl

    Code

    function loginCtrl($scope) {
        var vm = this;
    
        console.log($scope.$parent.$parent); // this would contain mainCtrl
    }
    

    Better approach would be to use controllerAs syntax or follow dot rule while defining objects so that prototypal inheritance gets followed.