Can a controller inherit scope from a parent controller when using ui-router

All we need is an easy explanation of the problem, so here it is.

I have the following:

var admin = {

   name: 'admin',
    url: '/admin',
    views: {
        'nav-sub': {
            templateUrl: '/Content/app/admin/partials/nav-sub.html',
            controller: function ($scope) { $scope.message = "hello"; }
        }
    },
    controller: ['$scope', function ($scope) {
        $scope.message = "hello";
    }]
}

var subject = {
    name: 'subject',
    parent: admin,
    url: '/subject',
    views: {
        '[email protected]': {
            templateUrl: '/Content/app/admin/partials/grid-subject.html',
            controller: 'AdminGridSubjectController',
        }
    }
};

I would like the AdminGridSubjectController to know what the $scope.message value is but it seems not to know anything about it. Is there something I am doing wrong?

stApp.controller('AdminGridSubjectController', ['$scope', function ( $scope ) {
    var a = $scope.message;
}]);

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

In order to access the scope of a parent controller in Angular UI Router use:

$scope.$parent

Then the parent scope is then freely available to you.

Method 2

Your problem might be that the name should reflect the parent in it:

var subject = {
    name: 'admin.subject',
    parent: admin,
    url: '/subject',
    ...

Here’s a complete illustration of how to inherit $scope with ui-router: plunker ex

Method 3

There are several ways (and workarounds) to access parent scope data … but controller inheritance itself, is not possible: https://github.com/angular-ui/ui-router/wiki/nested-states-&-nested-views#what-do-child-states-inherit-from-parent-states

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply