Can a controller inherit scope from a parent contr

2020-06-17 05:05发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2020-06-17 05:16

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.

查看更多
混吃等死
3楼-- · 2020-06-17 05:29

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楼-- · 2020-06-17 05:37

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

查看更多
登录 后发表回答