7

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: {
        'grid@': {
            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;
}]);

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work for views. The child view cannot access the non-root scope properties of the parent that contains the view. They just don't exist and aren't exposed properly.
I have been looking for hours! thanx a bunch
0

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

4 Comments

schwarts - Thanks Ben. I tried this but I still have the problem. I am wondering if this is something to do with the fact that I am using views.
@Anne It's the view's problem.
Shouldn't need that if you declare parent, right? Also, can you use a string instead of an object reference? Like, { ..., parent: 'admin', ... }? Thx!
When using the dot notation there is no need to specify the parent. This is in the most recent ui-router. Probably different back then.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.