AngularJS Controllers Nested Controllers


Example

Nesting controllers chains the $scope as well. Changing a $scope variable in the nested controller changes the same $scope variable in the parent controller.

.controller('parentController', function ($scope) {
    $scope.parentVariable = "I'm the parent";
});

.controller('childController', function ($scope) {
    $scope.childVariable = "I'm the child";

    $scope.childFunction = function () {
        $scope.parentVariable = "I'm overriding you";
    };
});

Now let's try to handle both of them, nested.

<body ng-controller="parentController">
    What controller am I? {{parentVariable}}
    <div ng-controller="childController">
        What controller am I? {{childVariable}}
        <button ng-click="childFunction()"> Click me to override! </button>
    </div>
</body>

Nesting controllers may have it's benefits, but one thing must be kept in mind when doing so. Calling the ngController directive creates a new instance of the controller - which can often create confusion and unexpected results.